I would like to create a custom validator that validates a field called description. The validation of this field is dependent on another field in this bean called category- if category is Other then description cannot be null or empty, if category is not Other then description has to be null or empty. I havent written a custom validator before and would appreciate any help. This is what I have so far (1) Create the @interface
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target(METHOD, FIELD, ANNOTATION_TYPE )
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=CategoryDescriptionValidator.class)
public @interface CategoryDescription {
String message() default "{description should be empty when category is not other}";
Class<?>[] groups() default {};
}
(2) Create the implementation - here I am confused as to how do I specify that the fields being compared are the Object's category and description fields?
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class CategoryDescriptionValidator implements ConstraintValidator<CategoryDescription,Object>{
@Override
public void initialize(CategoryDescription arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean isValid(Object arg0, ConstraintValidatorContext arg1) {
// TODO Auto-generated method stub
return false;
}
}
(3) In my bean(InformationBean) should I just do the following?
public class InformationBean{
private String category;
@CategoryDescriptionValidator
private String description;
}
Aucun commentaire:
Enregistrer un commentaire