Validating an Email Address in JSF
In earlier installments of the jAstrologer tutorial (see previous blogs) we used a converter and standard validators to validate the input in inputText components. You can also code your own validators if the standard JSF validatiors do not work for you. In our example, we will code a validator that checks a string to see if it is a valid email. To create a custom validator, you create a class that implements the javax.faces.validator.Validator interface and register the class in faces-config.xml. You can then use the validator using the <f:validator> tag.
- Right-click the project node and choose New > Java Class. Name the class EmailValidator, place it in the astrologer.validator package, and click Finish.
- In the class declaration, implement Validator as follows:
public class EmailValidator implements Validator { - Use the hint to implement the validate method.
- Add the following code to the validate method:
public void validate(FacesContext facesContext, UIComponent uIComponent, Object object) throws ValidatorException { String enteredEmail = (String)object; //Set the email pattern string Pattern p = Pattern.compile(".+@.+\\.[a-z]+"); //Match the given string with the pattern Matcher m = p.matcher(enteredEmail); //Check whether match is found boolean matchFound = m.matches(); if (!matchFound) { FacesMessage message = new FacesMessage(); message.setDetail("Email not valid"); message.setSummary("Email not valid"); message.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(message); } } - Open faces-config.xml and add the following code:
... </application> <validator> <validator-id>astrologer.EmailValidator</validator-id> <validator-class>astrologer.validate.EmailValidator</validator-class> </validator> </faces-config> - Open greeting.jsp and add the email field:
... <p>Enter your name: <h:inputText value="#{UserBean.name}" id="name" required="true"/> <h:message for="name" /></p> <p>Enter your email: <h:inputText value="email" id="email" required="true"> <f:validator validatorId="astrologer.EmailValidator" /> </h:inputText> <h:message for="email" /></p> <p>Enter your birthday: <h:inputText value="#{UserBean.birthday}" id="birthday" required="true"> ... - Run the project. When you enter a non-valid email in the field, you get
the following error:
Posted by Surya on May 27, 2006 at 01:13 AM CEST #
Posted by 192.18.240.11 on May 30, 2006 at 10:46 AM CEST #