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.5KB

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