To build a JSR303-based project environment, you need the following 4 artifacts:
Hibernate-validator-4.2.0.final.jar
Slf4j-api-1.6.1.jar
Validation-api-1.0.0.ga.jar
A simple Pojo, which uses the following validation rules:
PackageCom.test.request.bean;Importjava.util.Date;ImportJavax.validation.constraints.Max;Importjavax.validation.constraints.Min;ImportJavax.validation.constraints.NotNull;ImportJavax.validation.constraints.Past;ImportJavax.validation.constraints.Pattern;Importjavax.validation.constraints.Size;ImportOrg.hibernate.validator.constraints.Email; Public classInfobean {@NotNull (message= "Name cannot be empty!") @Min (value= 1, message = "ID can only be greater than or equal to 1, less than or equal to 10") @Max (value= ten, message = "ID can only be greater than or equal to 1, less than or equal to 10") PrivateInteger ID; @NotNull (Message= "Name cannot be empty!") @Size (min= 2, max = 4, message = "Name length must be between {min} and {Max}") @Pattern (regexp= "[\u4e00-\u9fa5]+", message = "Name can only be entered as Chinese characters") PrivateString UserName; @NotNull (Message= "Password cannot be empty!") @Size (min= 6, max =, message = "Password length must be between {min} and {Max}") PrivateString PassWord; @NotNull (Message= "Date cannot be empty!") @Past (Message= "You can only enter the past mention") PrivateDate birthday; @NotNull (Message= "Mail cannot be empty!") @Email (Message= "message format is incorrect") PrivateString email; set and get methods omitted here}
Since Pojo is also well defined, we also need to use the validatorfactory to obtain a sample factory instance and to help us complete the basic validation steps:
PackageCom.test.request.bean;Importjava.util.Date;ImportJava.util.Set;Importjavax.validation.ConstraintViolation;Importjavax.validation.Validation;ImportJavax.validation.Validator;Importjavax.validation.ValidatorFactory;Importorg.junit.Test; Public classinfobeantest {@Test Public voidTest ()throwsException {/*Create a validation plant*/validatorfactory validatorfactory=validation.builddefaultvalidatorfactory (); Validator Validator=Validatorfactory.getvalidator (); /*Information Encapsulation*/Infobean Infobean=NewInfobean (); Infobean.setid (-1); Infobean.setusername ("Zhang San"); Infobean.setpassword ("123456"); Infobean.setemail ("[Email protected]"); Infobean.setbirthday (NewDate ()); /*load the type for validation*/Set<ConstraintViolation<InfoBean>> set =validator.validate (Infobean); for(constraintviolation<infobean>Constraintviolation:set) System.out.println ("Error:" +constraintviolation.getmessage ()); }}
Hibernate Validator (JSR303) checksum