-1

I already have an email validator that works alright to check format of emails in the form of regular expression.

Now - I want to write another email validator in Java (since my application is on JSF, Glassfish 3.x) that does not allow non-government emails to be entered in the textbox. All domains like yahoo, gmail, hotmail etc. should not be accepted.

It should only accept Indian government domain based emails - @gov.in, @nic.in - all other emails should be rejected and the user should be suitably informed.

Requesting help in this regard. Thanks in advance.

DIM
  • 73
  • 1
  • 10

1 Answers1

4

I make e-mail validator based on the especification:

EmailValidator.java

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.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("com.lucio.EmailValidator")
public class EmailValidator implements Validator {

    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@(gov|nic)(\\.in)$";

    private Pattern pattern;
    private Matcher matcher;

    public EmailValidator(){
          pattern = Pattern.compile(EMAIL_PATTERN);
    }

    @Override
    public void validate(FacesContext context, UIComponent component,
            Object value) throws ValidatorException {

        matcher = pattern.matcher(value.toString());
        if(!matcher.matches()){

            FacesMessage msg = 
                new FacesMessage("E-mail validation failed.", 
                        "Invalid E-mail acepted only @gov.in or @nic.in");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);

        }

    }
}

For use:

<h:inputText id="email" value="#{user.email}" 
    label="Email Address">

    <f:validator validatorId="com.lucio.EmailValidator" />

</h:inputText>
  • What if it has to be a permutation of gov.in like @eicindia.gov.in - will the regex be 'private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@(*.gov|nic)(\\.in)$";' – DIM Jun 18 '15 at 13:52