KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exoplatform > faces > core > validator > EmailAddressValidator


1 /***************************************************************************
2  * Copyright 2001-2003 The eXo Platform SARL All rights reserved. *
3  * Please look at license.txt in info directory for more license detail. *
4  **************************************************************************/

5 package org.exoplatform.faces.core.validator;
6
7 import java.util.regex.*;
8 import javax.faces.context.FacesContext;
9 import javax.faces.component.UIComponent ;
10 import javax.faces.validator.Validator ;
11 import javax.faces.validator.ValidatorException ;
12 import org.exoplatform.faces.core.component.UIInput;
13 import org.exoplatform.faces.core.component.UIForm;
14 import org.exoplatform.faces.application.ExoFacesMessage ;
15 /**
16  * @author Tuan Nguyen (tuan08@users.sourceforge.net)
17  * @since Aug 13, 2004
18  * @version $Id: EmptyStringValidator.java,v 1.4 2004/08/19 14:53:44 tuan08 Exp $
19  */

20 public class EmailAddressValidator implements Validator {
21   static private Pattern emailPattern =
22     Pattern.compile("[a-zA-Z]([a-zA-Z0-9]+(\\.)?(\\-)?(\\_)?)*@[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]+)*");
23  
24   public void validate(FacesContext context,
25                        UIComponent component,
26                        Object JavaDoc value) throws ValidatorException {
27     if(component instanceof UIForm) {
28       UIForm.StringField field = (UIForm.StringField) value ;
29       Matcher matcher = emailPattern.matcher(field.getValue()) ;
30       if(!matcher.matches()) {
31         field.setError(true) ;
32         Object JavaDoc[] args = {field.getName(), field.getValue()} ;
33         throw new ValidatorException(new ExoFacesMessage("#{EmailAddressValidator.msg.invalid-email}", args)) ;
34       }
35     } else {
36       String JavaDoc s = (String JavaDoc) value ;
37       Matcher matcher = emailPattern.matcher(s) ;
38       if(!matcher.matches()) {
39         UIInput uiInput = (UIInput) component ;
40         Object JavaDoc[] args = {uiInput.getName(), s} ;
41         throw new ValidatorException(new ExoFacesMessage("#{EmailAddressValidator.msg.invalid-email}", args)) ;
42       }
43     }
44   }
45 }
Popular Tags