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?
There are several ways:
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.
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));
}
}
}
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>