In a Web application, it is necessary for the user to submit form data in order to ensure the validity of the data, and the validation of the foreground client, such as JavaScript, is not always secure and reliable, so we need a robust background validation framework to handle this problem. Fortunately, Java has released the JSR-303 interface standard, and there are many vendors that implement this standard, and the Hibernate Validator Verification framework is used more often.
Today in the processing of user-submitted ID card number This form field encountered a problem, you know our ID number earlier version only 15, and the second-generation ID number is 18, Hibernate validator @size annotations can only handle the minimum number of bits to the maximum number of bits, Instead of dealing with 15-bit or 18-bit situations, I thought of the need to use a custom annotation validator to solve the problem.
First we need to define a annotation:
@Documented @constraint (Validatedby = {Idconstraintvalidator.class}) @Target ({elementtype.method, Elementtype.field }) @Retention (retentionpolicy.runtime) public @interface idvalidator {String message () default "{ID}"; Class<?>[] Groups () default {}; class<? Extends payload>[] Payload () default {};}
Then define a class to handle the specific validation logic:
1 Public classIdconstraintvalidatorImplementsConstraintvalidator<idvalidator, string> {2 3 @Override4 Public voidInitialize (Idvalidator idvalidator) {5 6 }7 8 @Override9 Public BooleanIsValid (String ID, Constraintvalidatorcontext ctx) {Ten intLength =id.length (); One if(IsNumeric (ID) && (length = = | | length = = 18)) { A return true; - } - return false; the } -}
Finally, apply my annotations on the Pojo class:
1 Public Abstract classPersonImplementsSerializable {2 3 Private Static Final LongSerialversionuid = 1L;4 5@IDValidator (message= "{person.id.invalid}")6 PrivateString ID;7 8 PrivateString FirstName;9 Ten PrivateString LastName; One A PrivateString gender; - - Private intAge ; the - PublicString getId () { - returnID; -}
I put the error message in the resource file and omitted the page test description, but I showed the error message printed in the controller:
How to customize the validator of the JSR-303 standard