rozner
rozner

Reputation: 580

JSF2 converted and required on same input

I'm having an issue with converters and validators.

I have an input text which takes a CSV list. I have a converter that turns it into a list of String. This all works fine. Although I want to make the field required. But with the converter it seems to ignore any validator I attach as well as the required attribute on the input.

I attempted to solve this by throwing a converter Exception if the value is blank. This almost works, although it gets more complicated since I have a radio group just above that on the form with immediate=true. Immediate skips the validator just fine although seems to still attempt the converter. The next best thing I can think of is to validate in my action and add the faces message manually but I'd rather avoid that since I'll have to hard code the client ID into a Java class.

Any idea how to do this properly?

Upvotes: 0

Views: 118

Answers (1)

BalusC
BalusC

Reputation: 1108722

The converter is invoked before the validators.

Inside the converter, you just need to return null when the submitted value is null or an empty string.

@Override
public String getAsObject(FacesContext context, UIComponent component, Object value) {
    if (value == null || ((String) value).isEmpty()) {
        return null;
    }

    // ...
}

You should not throw a converter exception when the value is null or empty. This way the validators won't be fired. The converter should after all not validate the value, it should only convert the value.

Upvotes: 1

Related Questions