Change default message of f:validateRegex

15,703

Solution 1

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>

Solution 2

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"/>
Share:
15,703
user2783755
Author by

user2783755

Updated on June 04, 2022

Comments

  • user2783755
    user2783755 almost 2 years



    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.

  • Roland
    Roland about 4 years
    validatorMessage is being shown if any of the validators fail. The message should only appear for f:validateRegex only. I have the same here, that it is being shown for both validators.