title: Custom validator that compares two fields of a bean
body: <p>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</p>
  
  <pre><code>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&lt;?&gt;[] groups() default {};
  }
  </code></pre>
  
  <p>(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?</p>
  
  <pre><code>import javax.validation.ConstraintValidator;
  import javax.validation.ConstraintValidatorContext;
  public class CategoryDescriptionValidator implements ConstraintValidator&lt;CategoryDescription,Object&gt;{
  @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;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>(3) In my bean(InformationBean) should I just do the following?</p>
  
  <pre><code> public class InformationBean{
   private String category;
   @CategoryDescriptionValidator 
   private String description;
  }
  </code></pre>