我有电子邮件输入:
<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
但我想要类似"不正确的电子邮件…"的内容
谢谢
您可以使用inputText的validatorMessage
属性。在你的情况下,你可以使用这个:
<h:inputText value="#{registrationBean.email}" id="email" label="#{msgs.email}" validatorMessage="Incorrect e-mail…">
<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"/>
您可以使用验证器:
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>