12

入力フィールドごとにバリデーターごとに異なる検証メッセージを表示したいと思います。

<f:validateLongRange>JSFでは、入力フィールドごとに単一のバリデーター (例: ) に対して異なる検証メッセージを持つことは可能ですか?

4

1 に答える 1

16

いくつかの方法があります:

  1. 最も簡単なのは、validatorMessage属性を設定するだけです。

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

    ただし、これは他のバリデーターを使用する場合にも使用されます。Bean Validation を含む、入力フィールドに添付された他のバリデーターのすべてのメッセージをオーバーライドします。それが問題になるかどうかはわかりません。その場合は、次の方法に進んでください。

  2. あなたの場合のように、標準のバリデーターを拡張するカスタムバリデーターを作成し、目的のカスタムメッセージLongRangeValidatorでキャッチしValidatorExceptionて再スローします。例えば

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

    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. バリデータごとに異なるバリデータ メッセージを設定できるOmniFaces を使用します。<o:validator>

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

以下も参照してください。

于 2013-09-26T11:36:30.680 に答える