Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom JSF validator message for a single input field

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?

like image 430
Grolsch Avatar asked Sep 26 '13 11:09

Grolsch


1 Answers

There are several ways:

  1. The easiest, just set validatorMessage attribute.

    <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 Bean Validation. Not sure if that would form a problem then. If so, head to following ways.

  2. Create a custom validator which extends the standard validator, such as LongRangeValidator in your case, catch the ValidatorException and rethrow it with the desired custom message. E.g.

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

    with

    public class MyLongRangeValidator extends LongRangeValidator {
    
        public void validate(FacesContext context, UIComponent component, Object convertedValue) throws ValidatorException {
            setMinimum(0); // If necessary, obtain as custom attribute as well.
            setMaximum(42); // If necessary, obtain as custom 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="javax.faces.Required" message="Please fill out this field" />
        <o:validator validatorId="javax.faces.LongRange" minimum="0" maximum="42" message="Please enter a number between 0 and 42" />
    </h:inputText>
    

See also:

  • Change the default message "Validation Error: Value is required" to just "Value is required"
  • How to customize JSF conversion message 'must be a number consisting of one or more digits'?
  • Internationalization in JSF, when to use message-bundle and resource-bundle?
  • JSF converter resource bundle messages
like image 66
BalusC Avatar answered Oct 28 '22 02:10

BalusC