12

I'd like to have different validation messages for every validator for different input fields.

Is it possible in JSF to have a different validation messages for a single validator (e.g. <f:validateLongRange>) for every input field?

1 Answer 1

18

There are several ways:

  1. The easiest, just set the validatorMessage attribute of the UIInput component.

    <h:inputText ... validatorMessage="Please enter a number between 0 and 42">
        <f:validateLongRange minimum="0" maximum="42" />
    </h:inputText>
    

    However, this is also used when you use other validators. It will override all messages of other validators attached to the input field, including required="true" and Bean Validation such as @NotNull. Not sure if that would form a problem then. If so, then head to following ways.

  2. Create a custom validator which extends the validator of interest, such as LongRangeValidator in your specific case, wherein you catch the ValidatorException of the super.validate() call and then rethrow it with the desired custom message. E.g.

    <h:inputText ...>
        <f:validator validatorId="yourLongRangeValidator" />
        <f:attribute name="longRangeValidatorMessage" value="Please enter a number between 0 and 42" />
    </h:inputText>
    

    with

    @FacesValidator("yourLongRangeValidator")
    public class YourLongRangeValidator extends LongRangeValidator {
    
        public void validate(FacesContext context, UIComponent component, Object convertedValue) throws ValidatorException {
            setMinimum(0); // If necessary, obtain as custom f:attribute as well.
            setMaximum(42); // If necessary, obtain as custom f:attribute as well.
    
            try {
                super.validate(context, component, convertedValue);
            } catch (ValidatorException e) {
                String message = (String) component.getAttributes().get("longRangeValidatorMessage");
                throw new ValidatorException(new FacesMessage(message));
            }
        }
    }
    
  3. Use OmniFaces <o:validator> which allows setting a different validator message on a per-validator basis:

     <h:inputText ...>
         <o:validator validatorId="jakarta.faces.Required" message="Please fill out this field" />
         <o:validator validatorId="jakarta.faces.LongRange" minimum="0" maximum="42" message="Please enter a number between 0 and 42" />
     </h:inputText>
    

See also:

1
  • 1
    I will go for number 2 as I need different messages for different validation errors as well. Your solution approved my fear that I would need a solution beyond standard behaviour.
    – Grolsch
    Sep 26, 2013 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.