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 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.
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));
}
}
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With