package isrp.validators;

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 com.sun.faces.util.MessageFactory;

public class EmailValidator implements Validator {
	public static final String VALIDATOR_ID =
		"isrp.EmailValidator";
	public static final String INVALID_EMAIL_MESSAGE_ID =VALIDATOR_ID+".INVALID_EMAIL";
	
	public void validate(FacesContext context, UIComponent component,
			Object object) throws ValidatorException {
		String enteredEmail = (String) object;
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(enteredEmail);
		boolean matchFound = m.matches();

		if (!matchFound) {
			FacesMessage errMsg =
	            MessageFactory.getMessage(context,
	                INVALID_EMAIL_MESSAGE_ID);
			if (errMsg==null) errMsg=new FacesMessage("Incorrect email");
	            throw new ValidatorException(errMsg);
		}
	}

}
