/java/

Create custom annotation validators

2013-01-24 22:37:30

@NotEmpty(message="Name is required!")
@Column(name = "name")
@LowerCase(message="You can use only lower case")
@StringWithoutNumber(message="You can`t use number")
private String name;

Validator 1

package com.louis.core.validator;

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = StringWithoutNumberValidator.class)
@Documented
public @interface StringWithoutNumber{

    String message() default "";


    Class<? >[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
package com.louis.core.validator;

public class StringWithoutNumberValidator implements ConstraintValidator

<stringwithoutnumber, string=""> {

    public void initialize(StringWithoutNumber constraintAnnotation) {

    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        return !object.matches(".*\\d.*");
    }

}

Validator 2

package com.louis.core.validator;
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = LowerCaseValidator.class)
@Documented
public @interface LowerCase{

    String message() default "";


    Class<? >[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
public class LowerCaseValidator implements ConstraintValidator<lowercase, string=""> {

    public void initialize(LowerCase constraintAnnotation) {

    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        //return object.equals(object.toUpperCase());
        return object.equals(object.toLowerCase());
    }

}