更改f:validateRegex的默认消息

时间:2014-03-23 11:40:53

标签: validation jsf message



我输入了电子邮件:

<h:inputText value="#{registrationBean.email}" id="email" label="#{msgs.email}">
                        <f:validateLength minimum="5" maximum="50" />
                        <f:validateRegex
                                pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
                    </h:inputText>
                    <h:message for="email"/>

那么,当validateRegex不匹配时,我如何更改消息?现在消息是:

Regex pattern of '^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$' not matched

但是我想要“不正确的电子邮件......” 感谢。

2 个答案:

答案 0 :(得分:20)

您可以使用inputText的dataManager.brandArray[indexPath.row]属性。在您的情况下,您可以使用此:

validatorMessage

答案 1 :(得分:3)

您可以使用验证器:

public class EmailValidator implements Validator {
    private static Pattern patt = Pattern.compile(Constants.getEmailRegExp());
    @Override
    public void validate(FacesContext arg0, UIComponent comp, Object arg2)
            throws ValidatorException {
        if (arg2 == null || arg2.toString().trim().length() == 0) {
            return;
        }
        if (!patt.matcher(arg2.toString().trim()).matches()) {
            String label = (String) comp.getAttributes().get("label");
            throw new ValidatorException(new FacesMessage(
                FacesMessage.SEVERITY_ERROR, (label == null || label.trim().length() == 0 ? "Email: " : label+": ") +
                "Invalid format", null));
        }
    }
}

通过注释或faces-config.xml

注册
<validator>
    <validator-id>email-validator</validator-id>
    <validator-class>path.EmailValidator</validator-class>
</validator>

并使用它

<h:inputText id="email" label="#{msg.email}"
    value="#{registrationForm.email}"
    size="40" maxlength="80" required="true">
    <f:converter converterId="lowerCase" />
    <f:validator validatorId="email-validator" />
</h:inputText>