You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UsingBeanValidationToValidateInput.asciidoc 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. ---
  2. title: Using Bean Validation To Validate Input
  3. order: 45
  4. layout: page
  5. ---
  6. [[using-bean-validation-to-validate-input]]
  7. = Using Bean Validation to validate input
  8. Before you get started with Bean Validation you need to download a Bean
  9. Validation implementation and add it to your project. You can find one
  10. for instance at http://bval.apache.org/downloads.html. Just add the jars
  11. from the lib folder to your project.
  12. Bean Validation works as a normal validator. If you have a bean with
  13. Bean Validation annotations, such as:
  14. [source,java]
  15. ....
  16. public class Person {
  17. @Size(min = 5, max = 50)
  18. private String name;
  19. @Min(0)
  20. @Max(100)
  21. private int age;
  22. // + constructor + setters + getters
  23. }
  24. ....
  25. You can create a field for the name field as you always would:
  26. [source,java]
  27. ....
  28. Person person = new Person("John", 26);
  29. TextField firstName = new TextField("First name");
  30. setContent(firstName);
  31. ....
  32. and bind the field with a bean validation binder:
  33. [source,java]
  34. ....
  35. BeanValidationBinder<Person> binder = new BeanValidationBinder<>(Person.class);
  36. binder.forField(firstName).bind("name");
  37. binder.setBean(person);
  38. ....
  39. Your `firstName` field is now automatically validated based on the
  40. annotations in your bean class. You can do the same thing for the `age`
  41. field and you won't be able to set a value outside the valid 0-100
  42. range.
  43. A Bean Validation tutorial is available here:
  44. http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html