入力フィールドごとにバリデーターごとに異なる検証メッセージを表示したいと思います。
<f:validateLongRange>
JSFでは、入力フィールドごとに単一のバリデーター (例: ) に対して異なる検証メッセージを持つことは可能ですか?
入力フィールドごとにバリデーターごとに異なる検証メッセージを表示したいと思います。
<f:validateLongRange>
JSFでは、入力フィールドごとに単一のバリデーター (例: ) に対して異なる検証メッセージを持つことは可能ですか?
いくつかの方法があります:
最も簡単なのは、validatorMessage
属性を設定するだけです。
<h:inputText ... validatorMessage="Please enter a number between 0 and 42">
<f:validateLongRange minimum="0" maximum="42" />
</h:inputText>
ただし、これは他のバリデーターを使用する場合にも使用されます。Bean Validation を含む、入力フィールドに添付された他のバリデーターのすべてのメッセージをオーバーライドします。それが問題になるかどうかはわかりません。その場合は、次の方法に進んでください。
あなたの場合のように、標準のバリデーターを拡張するカスタムバリデーターを作成し、目的のカスタムメッセージ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));
}
}
}
バリデータごとに異なるバリデータ メッセージを設定できる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>