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("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)); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- java – 相同的字符串比较给我假
- java – 迭代每个可能的double值
- java – Lucene:相似类…如何定义几个相似性度量?
- java-我无法通过两步定义在黄瓜Spring Boot测试中使用@Spy对
- java必学必会之网络编程
- java – Jackson Object Mapper readvalue以字节为单位返
- java – Spring MVC中的@Controller注释和Controller类
- 如何从多个GUI类集成多页Java桌面应用程序
- Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL数据库的
- java – 在并行流中的hashmap中插入值时的线程安全性