这是领域:
<h:inputText id="mobilePhoneNo"
value="#{newPatientBean.phoneNo}"
required="true"
requiredMessage="Required"
validator="#{mobilePhoneNumberValidator}"
validatorMessage="Not valid (validator)"
converter="#{mobilePhoneNumberConverter}"
converterMessage="Not valid (converter)"
styleClass="newPatientFormField"/>
Run Code Online (Sandbox Code Playgroud)
验证者:
@Named
@ApplicationScoped
public class MobilePhoneNumberValidator implements Validator, Serializable
{
@Override
public void validate(FacesContext fc, UIComponent uic, Object o) throws ValidatorException
{
// This will appear in the log if/when this method is called.
System.out.println("mobilePhoneNumberValidator.validate()");
UIInput in = (UIInput) uic;
String value = in.getSubmittedValue() != null ? in.getSubmittedValue().toString().replace("-", "").replace(" ", "") : "";
if (!value.matches("04\\d{8}"))
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please enter a valid mobile phone number.", null));
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我按下窗体中的命令按钮时,我得到以下行为:
在所有三种情况下,都MobilePhoneNumberConverter.getAsObject()被称为.MobilePhoneNumberValidator.validate()是永远不会被调用.当该字段为空时,它会忽略该required="true"属性并直接进行转换.
我原以为正确的行为是:
注意:支持bean是请求范围的,因此这里没有花哨的AJAX业务.
更新:
它可能与javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL被设置有关true吗?
Bal*_*usC 13
转换在验证之前发生.当值为null空时,也将调用转换器.如果要将null值委托给验证器,那么您需要设计转换器,它只是null在提供的值为null空时返回.
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.trim().isEmpty()) {
return null;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
与具体问题无关,您的验证器存在缺陷.您不应该从组件中提取提交的值.它不是由转换器返回的值相同.正确提交和转换的值已作为第3个方法参数提供.
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null) {
return; // This should normally not be hit when required="true" is set.
}
String phoneNumber = (String) value; // You need to cast it to the same type as returned by Converter, if any.
if (!phoneNumber.matches("04\\d{8}")) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please enter a valid mobile phone number.", null));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9628 次 |
| 最近记录: |