单个输入字段的定制JSF验证器消息 [英] Custom JSF validator message for a single input field

查看:106
本文介绍了单个输入字段的定制JSF验证器消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为不同输入字段的每个验证器提供不同的验证消息.

I'd like to have different validation messages for every validator for different input fields.

在JSF中是否可以为每个输入字段的单个验证器(例如<f:validateLongRange>)使用不同的验证消息?

Is it possible in JSF to have a different validation messages for a single validator (e.g. <f:validateLongRange>) for every input field?

推荐答案

有几种方法:

  1. 最简单的方法就是设置validatorMessage属性.

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

但是,当您使用其他验证器时,也会使用它.它将覆盖附加到输入字段的其他验证器的所有消息,包括Bean验证.不知道那是否会构成问题.如果是这样,请遵循以下方法.

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.

创建一个扩展标准验证器的自定义验证器,例如 LongRangeValidator ,捕获ValidatorException并使用所需的自定义消息将其重新抛出.例如

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>

使用

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

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

  • 另请参见:

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆