java – JSF转换器导致验证器被忽略

这是领域:
<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"/>

验证者:

@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));
        }
    }
}

当我按下窗体中的命令按钮时,我得到以下行为:

>当该字段为空时,消息为“无效(转换器)”.
>当字段具有有效条目时,消息为“无效(验证器)”.
>当字段的条目无效时,消息为“无效(转换器)”.

在所有三种情况下,都会调用MobilePhoneNumberConverter.getAsObject().永远不会调用MobilePhoneNumberValidator.validate().当该字段为空时,它会忽略required =“true”属性并直接进行转换.

我原以为正确的行为是:

>当该字段为空时,该消息应为“必需”.
>当字段具有有效条目时,根本不应有任何消息.
>当字段的条目无效时,消息应为“无效(验证器)”.
>如果某种可能性,通过转换传递的验证没有,则消息应为“无效(转换器)”.

注意:支持bean是请求范围的,因此这里没有花哨的AJAX业务.

更新:

它可能与javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL设置为true有关吗?

解决方法

转换在验证之前发生.当值为null或为空时,也将调用转换器.如果要将null值委托给验证器,则需要设计转换器,当提供的值为null或为空时,它只返回null.
@Override
public Object getAsObject(FacesContext context,UIComponent component,String value) {
    if (value == null || value.trim().isEmpty()) {
        return null;
    }

    // ...
}

与具体问题无关,您的验证器存在缺陷.您不应该从组件中提取提交的值.它与转换器返回的值不同.正确提交和转换的值已作为第3个方法参数提供.

@Override
public void validate(FacesContext context,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,null));
    }
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...