All blog posts, code samples and downloads licensed under Apache License 2.0.

Custom validator for email adresses

Oliver Busse on 20.10.2013 13:06:04 CEDT, filed under XSP Java 

In addition to my XSnippet I just updated the code to validate a field that should hold a valid email adress. This one is a different approach and I show the whole setup process for that purpose.

// this is the Java code of the validator
package com.hp;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class EmailValidator implements Validator {
	public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
		if (!value.toString().matches("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")) {
			FacesMessage message = new FacesMessage("Invalid E-Mail adress");
			// context.addMessage(component.getClientId(context), message);
			throw new ValidatorException(message);

<!-- this is the faces-config.xml entry -->

<!-- this is the implementation in the XPage -->
<xp:inputText value="#{comment.commentEmail}" id="commentEmail1" required="true" style="width:100%">
		<xp:validateRequired message="Please provide your E-Mail">

		<xp:validator validatorId="emailValidator">

Please note that the field has to define a required validator to process you custom validator in addition.

Tagged with java email field validation