views:

90

answers:

1

I'm trying to create a simple custom validator for my project, and I can't seem to find a way of getting seam to validate things conditionally.

Here's what I've got:

A helper/backing bean (that is NOT an entity)

@RequiredIfSelected
public class AdSiteHelper {
  private Date start;
  private Date end;
  private boolean selected;
  /* getters and setters implied */
}

What I need is for "start" and "end" to be required if and only if selected is true.

I tried creating a custom validator at the TYPE target, but seam doesn't seem to want to pick it up and validate it. (Maybe because it's not an entity?)

here's the general idea of my custom annotation for starters:

@ValidatorClass(RequiredIfSelectedValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredIfSelected {
    String message();
}

public class RequiredIfSelectedValidator implements Validator<RequiredIfSelected>, Serializable {
  public boolean isValid(Object value) {
    AdSiteHelper ash = (AdSiteHelper) value;
    return !ash.isSelected() || (ash.getStart() && ash.getEnd());
  }
  public void initialize(RequiredIfSelected parameters) { }
}
+1  A: 

I had a similar problem covered by this post. If your Bean holding these values is always the same then you could just load the current instance of it into your Validator with

//Assuming you have the @Name annotation populated on your Bean and a Scope of CONVERSATION or higher
AdSiteHelper helper = (AdSiteHelper)Component.getInstance("adSiteHelper");

Also as you're using Seam your validators don't need to be so complex. You don't need an interface and it can be as simple as

@Name("requiredIfSelectedValidator")
@Validator
public class RequiredIfSelectedValidator implements javax.faces.validator.Validator {
   public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
      //do stuff
   }
}
Damo