Spring MVC Hibernate custom validator annotation. - Tuong-Nguyen/Spring GitHub Wiki
Custom Annotation:
- Beside the original annotations, Hibernate validation also allow we create the custom validations. This wiki will epitomize how to create an custom hibernate validation via annotation.
- To know more about hibernate custom validation you can refer here
Create an annotation:
//Defines the supported target element types. Where the annotation can be use
@Target({FIELD,METHOD,PARAMETER, ANNOTATION_TYPE})
//Specifies, that annotations of this type will be available at runtime by the means of reflection
@Retention(RUNTIME)
//Marks the annotation type as constraint annotation and specifies the validator to be used to validate elements annotated
@Constraint(validatedBy = CheckPassValidator.class)
//Says, that the use of @CheckPass will be contained in the JavaDoc of elements annotated with it
@Documented
public @interface CheckPass {
//define the default message.
String message() default "The password is not enought strong!";
//Attribute anable to set groupt that the annotation belong.
Class<?>[] groups() default {};
//Attribute anable to set load level of the annotation.
Class<? extends Payload>[] payload() default{};
//Custom attributes which will be options when we use the annotation(ex: @Checkpass(upcase = true, lowcase = false))
boolean upcase() default true;
boolean lowcase() default true;
boolean specialcharacter() default true;
}
Create the validator class:
- This validator class is store the validation methods which will be use to validate.
public class CheckPassValidator implements ConstraintValidator<CheckPass, String> {
private boolean upcase;
private boolean lowcase;
private boolean specialcharacter;
@Override
public void initialize(CheckPass constraintAnnotation) {
this.upcase = constraintAnnotation.upcase();
this.lowcase = constraintAnnotation.lowcase();
this.specialcharacter = constraintAnnotation.specialcharacter();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if(value == null){
return false;
}
String regex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(value);
if(!matcher.matches())
return false;
return true;
}
}
Use:
@CheckPass(message = "The password must contain numberic character, lowcase character, upcase character, special character, and more then 8 chararcters")
private String pass;