1

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.

Real Chembil
  • 261
  • 2
  • 7
  • 23
  • 2
    Not familiar with JSF, but can you write "or" operators in patterns? Then the pattern would become `"(^$|^A-Za-z-_./\s]{2,50}$)"` for "either the empty string, or 2 or more letters" – Mr Lister Aug 28 '13 at 10:24
  • Which JSF impl/version are you using? This construct works fine for me. The validate regex is not invoked if field is blank. By the way, you forgot `maxlength="50"` on the field. – BalusC Aug 28 '13 at 11:48
  • @balusc I am using jsf-impl-2.0.3-b05.jar. – Real Chembil Aug 28 '13 at 11:54
  • Wow, that's ancient (3 years old). There are currently already more than 30 newer releases. The latest is 2.1.25 (do not grab 2.2.x yet). Go get it here: http://javaserverfaces.java.net and retry. By the way, don't be surprised if you see 100 other (minor) problems and annoyments instantly being fixed with this major upgrade step. – BalusC Aug 28 '13 at 11:56
  • Thanks @BalusC , I tested with the new 2.1.25 impl javax.faces-2.1.25.jar. Still the same issue. I feel it's something to do with the regex pattern. – Real Chembil Aug 28 '13 at 12:12

1 Answers1

7

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}$" />
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Many years later this helped me. Seems odd that it's not the default behaviour for numbers using f:validateLongRange. – Edward Sep 17 '20 at 01:59