Custom validation
Hibernate Validate provides rich built-in validation annotations. When these do not meet your requirements, we can customize the validation annotations.
For example, we customize a keyword filtering validation rule, and the annotation is as follows.
1. Write validation rule annotation class
package com.yyoo.springmvc.valid; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE, ElementType.TYPE_USE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = {KeyWordValidator.class}) @Documented @Repeatable(KeyWord.List.class) public @interface KeyWord { String message() default "{com.yyoo.springmvc.valid.KeyWord.message}"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; String keyWords() default ""; @Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @interface List { KeyWord[] value(); } }
Interpretation of several meta annotations
- @Target ({ElementType. FIELD, ElementType. METHOD, ElementType. PARAMETER, ElementType. ANNOTATION_TYPE, ElementType. TYPE_USE}): defines the target element types supported by the constraint@ KeyWord can be used for fields (element type FIELD), JavaBeans attributes, and METHOD return values (METHOD), METHOD / constructor parameters (parameters), and type parameters of parameterized types (TYPE_USE). Element type annotation_ Type allows you to create constraints based on @ KeyWord.
- @Retention(RetentionPolicy.RUNTIME): annotations of this type will be available through reflection at run time (this method is generally used in our definition)
@Constraint(validatedBy = {KeyWordValidator.class}): mark the annotation type as constraint annotation and specify the corresponding validator class as KeyWordValidator (the validator is defined below). If constraints can be used for multiple data types, you can specify multiple validators, one for each data type. - @Documented: will annotations be included in JavaDoc
- @Repeatable(List.class): indicates that annotations can be repeated multiple times in the same place, usually with different configurations. List is the internal annotation list defined in our annotation class.
Validation annotations have the following necessary properties
- Message: error message attribute. We set the default value {com.yyoo.springmvc.valid.KeyWord.message}, indicating that it will read the message configuration of the internationalization file
- groups: Specifies the authentication group. This must default to class <? > An empty array of type.
- Payload: clients of the Jakarta Bean Validation API can use this property to assign custom payload objects to constraints. The API itself does not use this property.
Custom properties
In the example, the keyWords attribute is our custom attribute, which can be defined according to our own needs.
Internal note List
It allows @ CheckCase to specify multiple comments on the same element, such as using different validation groups and messages. Although another name can be used, the Jakarta Bean validation specification recommends using List and making the annotation an internal annotation of the corresponding constraint type.
2. Define the verifier class KeyWordValidator
package com.yyoo.springmvc.valid; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class KeyWordValidator implements ConstraintValidator<KeyWord,String> { private String keyWords; @Override public void initialize(KeyWord constraintAnnotation) { // Import the value initialized on the annotation this.keyWords = constraintAnnotation.keyWords(); } @Override public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) { // A simple rule that does not pass if it contains keywords if(this.keyWords.contains(s)){ return false; } return true; } }
Javax. Validation. Constraintvalidator < a extensions annotation, t > interface
Each custom verifier needs to implement this interface
The initialize method provides the initialization of the verifier. As our example, we import the keyWords attribute assigned when using annotations into our current verifier. Then use it in the isValid method.
ConstraintValidatorContext
Our example does not use this parameter. However, for example, we need to define some other prompt information in the verifier, which can be used as follows:
if ( !isValid ) { constraintContext.disableDefaultConstraintViolation(); constraintContext.buildConstraintViolationWithTemplate( "{com.yyoo.springmvc.valid.KeyWord.other.message}" ) .addConstraintViolation(); }
For more advanced usage and functions (such as custom validation annotation, custom cross validation, etc.), please refer to Hibernate Validator
Previous: 006 spring MVC parameter validation 2 - group validation
Next: 008 spring MVC viewresolver view resolver