ImportJava.util.Iterator;Importjava.util.List;ImportJavax.validation.ConstraintValidator;ImportJavax.validation.ConstraintValidatorContext;Importorg.apache.commons.lang3.StringUtils; Public classListstringpatternvalidatorImplementsConstraintvalidator<liststringpattern, list<string>> { PrivateString pattern; PrivateString message; Public voidInitialize (Liststringpattern constraintannotation) { This. Pattern =Constraintannotation.regexp (); This. Message =Constraintannotation.message (); } Public BooleanIsValid (list<string>list, Constraintvalidatorcontext constraintcontext) { if(List = =NULL) { return true; } String errorstring=NULL; BooleanIsValid =true; if(Pattern = =NULL|| "". Equals (Pattern.trim ())) {IsValid=false; if(!isValid) {constraintcontext.disabledefaultconstraintviolation (); Constraintcontext.buildconstraintviolationwithtemplate ("The specified regular expression is empty"). Addconstraintviolation (); } returnIsValid; } Else{Iterator<String> iter =List.iterator (); while(Iter.hasnext ()) {string string=Iter.next (); if(!string.matches (pattern)) {IsValid=false; ErrorString=string; Break; } } } if(!isValid) {constraintcontext.disabledefaultconstraintviolation (); String message= This. Message; if(Stringutils.isblank (message)) {message= "List<string> is empty, or" + errorstring + "does not conform to regular expression:" +pattern;; } constraintcontext.buildconstraintviolationwithtemplate (Message). Addconstraintviolation (); } returnIsValid; }}
Importjava.lang.annotation.Documented;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.Target;Importjava.lang.annotation.*;ImportJavax.validation.Constraint;ImportJavax.validation.Payload;/*** Custom Validator * Check parameters in List<string> * <pre> * @ListStringPattern (RegExp = "", message = "") * </pre> *
@authorRONG.E **/@Target ({elementtype.method, Elementtype.field, Elementtype.annotation_type}) @Retention ( Retentionpolicy.runtime) @Constraint (Validatedby= Liststringpatternvalidator.class) @Documented Public@InterfaceListstringpattern {String message ()default"String in List no match pattern"; Class<?>[] Groups ()default {}; Class<?extendsPayload>[] Payload ()default {}; String RegExp (); /*** defines several {@linkListstringpattern} annotations on the same element. * * @seeListstringpattern*/@Target ({elementtype.method, Elementtype.field, Elementtype.annotation_type, Elementtype.constructor, Elementtype.parameter}) @Retention (retentionpolicy.runtime) @Documented @InterfaceList {liststringpattern[] value (); }}
Javax.validation Custom Validator