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

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

问题描述

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

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

在 JSF 中是否可以为每个输入字段的单个验证器(例如 )提供不同的验证消息?

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天全站免登陆