在JSF中具有最小长度验证的可选字段 [英] Optional field with minimum length validation in JSF

查看:51
本文介绍了在JSF中具有最小长度验证的可选字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有可选字段的注册表,但是如果您输入任何值,则该字段应超过2个字符. 如果用户将该字段留空,如何跳过验证?

I have a registration form with an optional field but if you enter any value it should be more than 2 characters. How to skip validation if the user leaves the field blank?

 <h:inputText id ="fooid" maxlength="50" tabindex="4" value="#{registrationBean.foo}"  validatorMessage="Please enter two or more characters">
 <f:validateRegex pattern="^[A-Za-z-_./\s]{2,50}$"/>
 <f:ajax event="blur" render="fooPanel" />
 </h:inputText>

任何帮助将不胜感激.

推荐答案

如果添加以下上下文参数,它将按预期工作:

It works as intented if you add the following context parameter:

<context-param>
    <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
    <param-value>true</param-value>
</context-param>

这将告诉JSF将空字符串提交的值解释为null.如果值为null,则仅触发required="true"验证程序,而其他验证程序则不会触发.另一个优势是,当最终用户不填写输入内容时,它可以使您的模型摆脱混乱的空字符串.

This will tell JSF to interpret empty string submitted values as null. If a value is null, then only the required="true" validator will be triggered and other validators not. Additional advantage is that it keeps your model free of cluttered empty strings when the enduser didn't fill out the inputs.

如果由于某种原因这不是一个选择,例如当您的模型错误地依赖于空字符串时,那么最好的选择是也要在正则表达式中检查空字符串:

If this is not an option for some reason, e.g. when your model is incorrectly relying on empty strings, then your best alternative is to check in regex for empty string as well:

 <f:validateRegex pattern="^$|^[A-Za-z-_./\s]{2,50}$" />

这篇关于在JSF中具有最小长度验证的可选字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆