Sometimes existing validation annotations do not meet some of the business requirements, so there is an extension of custom annotations.
1. Adding annotation classes
import javax.validation.constraint;import javax.validation.payload;import java.lang.annotation.documented;import java.lang.annotation.retention;import Java.lang.annotation.target;import static java.lang.annotation.elementtype.*;import static java.lang.annotation.ElementType.PARAMETER;import static java.lang.annotation.retentionpolicy.runtime;/** * user: zhoujingjie * date: 14-10-31 * time: pm 6:00 */@Target ({ method, field, annotation_type, CONSTRUCTOR,&NBSP;PARAMETER&NBSP) @Retention (RUNTIME) @Documented @constraint (validatedby = { Phonenovalidator.class}) public @interface phoneno { //default error message string message () default "phone number error"; //Group class<?>[] groups () default { }; //load &NBSP;&NBSP;&NBsp; class<? extends payload>[] payload () default { }; //use @Target when specifying multiple ({ field, method, parameter, ANNOTATION_TYPE&NBSP,}) @Retention (RUNTIME) @Documented @interface List { PhoneNo[] Value (); }}
Custom annotations require custom validator, so the variables in the annotations are not mandatory and can be either a message or a
2. Add Phonenovalidator
import org.apache.commons.lang.stringutils;import javax.validation.constraintvalidator;import javax.validation.constraintvalidatorcontext;/** * Mobile phone number verification * user: zhoujingjie * Date: 14-11-1 * Time: Morning 10:45 */public class phonenovalidator implements constraintvalidator<phoneno,string> { @Override public void initialize (phoneno constraintannotation) { } @Override public boolean isvalid (String value, constraintvalidatorcontext context) { if ( Stringutils.isempty (value)) return true; if (Value.matches ("(\\+86) | ( (1[3|4|5|8]\\d{9} ")) {&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; return true; } return false; }}
3. Finally
Complete, a simple custom annotation is completed. Use the same way as other annotations
SPRINGMVC Bean Validator Custom annotations