Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 views
in Technique[技术] by (71.8m points)

validation - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...