微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/java/127759.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐