Validating Email Addresses with JSF2, Ajax + Bean Validation

Recently, I was looking for a way, to validate Email-Addresses with JSF.
I came accross this blog post on java.net:

It shows, how this would have been done in the old JSF 1.1/1.2 ways… But we’re in 2010 and do it now the following way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
...
            <h:panelGroup id="loginRegisterBox" layout="block">
                <p>
                    <h:outputLabel for="userEmail" value="#{bundle['register.emailaddress']}"/>
                    <h:inputText id="userEmail" value="#{loginRegisterBean.email}"
                                 validatorMessage="#{bundle.register_invalidEmail}"
                                 required="true"
                                 requiredMessage="#{bundle.registration_please_enter_email}"
                                >
                        <f:ajax event="change" execute="@this userEmail authorBox" render="@this loginRegisterBox"
                                listener="#{loginRegisterBean.emailChanged}"/>
                        <f:validateRegex pattern=".+@.+\.[a-z]+"/>
                    </h:inputText>
                    <h:message for="userEmail"/>
                </p>
....
</h:panelGroup>
....

What does this code? It sets the email property of the bean loginRegisterBean after the user changed the value and clicked out of the field (through ajax). It automatically validates the email address through the f:validateRegex pattern and updates the message ( h:message ) if the validation failed.

The Bean looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Named(value = "loginRegisterBean")
@SessionScoped
public class LoginRegisterBean implements Serializable {
 
....
 
     // also apply these restrictions on the property itself!
    @Pattern(regexp = ".+@.+\\.[a-z]+")
    @NotNull
    private String email;
....
    public void emailChanged(AjaxBehaviorEvent event) {
// do something
    }
...
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *