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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. BeanItem<Person> item = new BeanItem<Person>(person);
  31. TextField firstName = new TextField("First name",
  32. item.getItemProperty("name"));
  33. firstName.setImmediate(true);
  34. setContent(firstName);
  35. ....
  36. and add the bean validation as a normal validator:
  37. [source,java]
  38. ....
  39. firstName.addValidator(new BeanValidator(Person.class, "name"));
  40. ....
  41. Your `firstName` field is now automatically validated based on the
  42. annotations in your bean class. You can do the same thing for the `age`
  43. field and you won't be able to set a value outside the valid 0-100
  44. range.
  45. A Bean Validation tutorial is available here:
  46. http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html