Built-in constraints in Bean Validation
@Null The annotated element must be null
@NotNull The annotated element must not be null
@AssertTrue The annotated element must be true
@AssertFalse The annotated element must be false
@Min(value) The annotated element must be a number, and its value must be greater than or equal to the specified minimum value.
@Max(value) The annotated element must be a number, and its value must be less than or equal to the specified maximum value.
@DecimalMin(value) The annotated element must be a number, and its value must be greater than or equal to the specified minimum value
@DecimalMax(value) The annotated element must be a number, and its value must be less than or equal to the specified maximum value
@Size(max=, min=) The size of the annotated element must be within the specified range.
@Digits (integer, fraction) The annotated element must be a number and its value must be within an acceptable range.
@Past The annotated element must be a past date
@Future The annotated element must be a future date
@Pattern(regex=,flag=) The annotated element must comply with the specified regular expression
Hibernate Validator attached constraint
@NotBlank(message =) Verify that the string is not null and must be greater than 0
@Email The annotated element must be an email address
@Length(min=,max=) The size of the annotated string must be within the specified range.
@NotEmpty The commented string must be non-empty
@Range(min=,max=,message=) The annotated element must be within the appropriate range
Effects and advantages
Let's see the final effect first:
public class UserEntity { @Password private String password; @Email private String email;}The above uses two custom annotations to verify password and email. The advantage of this is: one definition is used everywhere. When modifying the verification rules, you just need to modify the annotations. If you customize it, use the tag provided by hibernate:
@Pattern(regexp="...")private String email;
If you suddenly need to modify the verification rule regexp after writing many classes, the workload will be much greater at this time.
accomplish
First, introduce the hibernate validation dependency and add:
<!-- hibernate validator --> <!-- hibernate verification framework --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.2.Final</version> </dependency>
hibernate validation is a reference implementation of JSR, so use it for bean verification.
Customizing a verification annotation is divided into three steps:
The first step is to create annotations:
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })@Retention(RUNTIME)@Documented@Constraint(validatedBy = { EmailValidator.class })public @interface Email { String message() default "This is not a valid email format"; /** * @return the regular expression to match */ String regexp() default "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9]+//.[a-zA-Z]{2,4}"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; /** * Defines several {@link Size} annotations on the same element. * * @see Size */ @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented @interface List { Email[] value(); }} Create annotations through the @interface keyword, and each method is a parameter of the annotation. For example, in the above code, you can use @Email(regexp="...",message="...") like this. You can ignore the rest, just copy it directly. It should be noted that @Constraint(validatedBy = { EmailValidator.class }) , here specifies the verification class of the annotation and replaces the class name according to the actual situation.
The second step is to create a verification class:
public class EmailValidator implements ConstraintValidator<Email, String>{ private String regexp; @Override public void initialize(Email constraintAnnotation) { this.regexp = constraintAnnotation.regexp(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if(value==null){return true;} if( value.matches(regexp)){ return true; } return false; }} Here, just implement ConstraintValidator<Email, String> interface and create a validator. The initialize method gets the annotated regexp value, and isValid method is verified. If it meets the regular expression, it returns true, otherwise it returns false.
It should be noted that when the value is empty, that is, when the verification object is not initialized, the corresponding verification rules must be written, otherwise an error will be reported. In the above code, what is written is:
if(value==null){return true;}That is, when the verification object is empty, it returns success.
The third step is to write the default error message. In fact, this step has been done in the first step, through default, so this step does not need to be done.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.