问题
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