我在名为“com.travstar.validators”的包“com.travstar.validators”中的项目中创建了一个验证器,名为EmailValidator。
课程内容:
package com.travstar.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.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator("emailValidator")
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);
}
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
{
matcher = pattern.matcher(value.toString());
if (!matcher.matches())
{
FacesMessage msg = new FacesMessage("Email validation failed.", "Invalid Email format.");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}
我实现了这样的电子邮件验证:
<h:panelGrid columns="1" width="100%">
<h:outputText value="Email Address"></h:outputText>
<h:inputText id="emailAddress" value="#{passengerDetailsBean.contactDetails.emailAddress}" styleClass="input-block-level" placeholder="" required="true">
<f:validator validatorId="emailValidator"></f:validator>
</h:inputText>
<h:message for="emailAddress" styleClass="alert alert-error" />
</h:panelGrid>
这或多或少与我在网上找到的教程完全一样,但我无法让它工作。
在我点击页面的那一刻,抛出以下异常:
javax.servlet.ServletException: Unknown validator id 'emailValidator'
我正在使用 JSF 2.1,据我所知,我不需要摆弄 faces.config.xml
任何人对为什么会发生这种情况有任何想法?