0,我正在尝试为电子邮件进行自定义验证。以下是我的电子邮件验证码:
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);
}
}
}
以下是我的Login.xhtml文件编码:
Enter your email :
<h:inputText id="email" value="#{user.email}"
size="20" required="true" label="Email Address">
<f:validator validatorId="checkemail" />
</h:inputText>
现在我遇到了以下错误:
javax.servlet.ServletException: Expression Error: Named Object: checkemail not found.
javax.faces.webapp.FacesServlet.service(FacesServlet.java:422)
那么请帮助我解决什么问题?
答案 0 :(得分:3)
faces-config.xml
声明符合JSF 2.x。/META-INF/faces-config.xml
文件。/WEB-INF/lib
。 无关,验证器中存在线程安全问题。 matcher
不能声明为实例变量。将其声明为方法局部变量。验证者的另一个与JSF无关的问题是允许电子邮件地址since 2010包含非拉丁字符,例如阿拉伯语,希伯来语,CJK等。Update your regex。