Skip to content

Instantly share code, notes, and snippets.

@Baztoune
Created August 8, 2012 14:46
Show Gist options
  • Save Baztoune/3295571 to your computer and use it in GitHub Desktop.
Save Baztoune/3295571 to your computer and use it in GitHub Desktop.
Email validation with RegExp (JSF validator + Seam component)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
@Name("myEmailValidator")
@BypassInterceptors
@org.jboss.seam.annotations.faces.Validator
public class EmailValidator implements Validator {
private static final String EMAIL_REGEX = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";
/**
* <a href="http://www.mkyong.com/regular-expressions/how-to-validate-email
* -address-with-regular-expression/">Source</a> <br/>
* Modification : autorisation des "-" dans le nom de domaine <br/>
* Exemple valide : jean-michel-75440.exemple42@email-pro.mon-entreprise.com
*/
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
/* Create the correct mask */
Pattern mask = Pattern.compile(EMAIL_REGEX);
/* Get the string value of the current field */
String emailField = (String) value;
/* Check to see if the value is a valid email */
Matcher matcher = mask.matcher(emailField);
if (!matcher.matches()) {
FacesMessage message = new FacesMessage();
message.setSummary("Email invalide");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment