Optional field with minimum length validation in JSF

一笑奈何 提交于 2019-12-24 10:57:31

问题


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>

Any help would be appreciated.


回答1:


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>

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}$" />


来源:https://stackoverflow.com/questions/18485090/optional-field-with-minimum-length-validation-in-jsf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!