加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 03:15:36 所属栏目:Java 来源:网络整理
导读:这是领域: h:inputText id="mobilePhoneNo" value="#{newPatientBean.phoneNo}" required="true" requiredMessage="Required" validator="#{mobilePhoneNumberValidator}" validatorMessage="Not valid (validator)" converter="#{mobilePhoneNumberConvert
这是领域:
<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("04d{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("04d{8}")) {
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,null));
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读