Reputation: 588
I have input for email:
<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"/>
So, how I can change message, when validateRegex not matched? Now message is:
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
But I want something like „Incorrect e-mail…”
Thanks.
Upvotes: 3
Views: 17047
Reputation: 1138
You can use the validatorMessage
attribute of inputText. In your case you can use this:
<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"/>
Upvotes: 24
Reputation: 3728
You can use validator:
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));
}
}
}
Register it via annotation or in faces-config.xml
:
<validator>
<validator-id>email-validator</validator-id>
<validator-class>path.EmailValidator</validator-class>
</validator>
And use it
<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>
Upvotes: 3