2

0 and i m trying to make custom validation for email.Following is the my email validator code:

package customValidator;

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("checkemail")
public class EmailValidator implements Validator{

    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\." +
            "[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*" +
            "(\\.[A-Za-z]{2,})$";

    private Pattern pattern;
    private Matcher matcher;

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



    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 format.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);

        }

    }

}

and following is my Login.xhtml file coding:

Enter your email :

                <h:inputText id="email" value="#{user.email}" 
                    size="20" required="true" label="Email Address">
                    <f:validator validatorId="checkemail" />
                </h:inputText>

Now i m getting following error:

javax.servlet.ServletException: Expression Error: Named Object: checkemail not found.
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:422)

So please help me that what should be solution?

Lumia
  • 121
  • 5
  • 13

1 Answers1

3
  • Make sure that your faces-config.xml is declared conform JSF 2.x.
  • Make sure that the class is really in a package.
  • Make sure that there's no typo in the validator ID (whitespace!).
  • Make sure that you've properly rebuilt/redeployed/restarted the code/WAR/server.
  • If the class is actually embedded in a JAR file
    • Make sure that the JAR has a JSF 2.x compatible /META-INF/faces-config.xml file.
    • Make sure that it ends up in /WEB-INF/lib of the WAR.

Unrelated to the concrete problem, you've a threadsafety problem in your validator. The matcher must not be declared as instance variable. Declare it as method local variable instead. Another, not JSF-related, problem with your validator is that email addresses are since 2010 allowed to contain non-latin characters such as Arabic, Hebrew, CJK, etc. Update your regex.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555