Search code examples
validationjsf-2primefaces

Validation for non-required field


I have these lines of code to validate for an e-mail address:

<h:outputText value="#{labels.eMail}: " />
<p:inputText size="30" maxlength="50" validatorMessage="Please provide a valid e-mail address" value="#{personelView.eMail}">
  <f:validateRegex pattern=".+@.+\.[a-zA-Z]+" />
</p:inputText>

When I leave the e-mail address field empty and submit the form it gives validation error. Why JSf is doing this? Isn't it supposed to just validate e-mail field with the above code? I even tried adding:

required="false" 

still no good. Does anyone have any idea about this case?


Solution

  • your inputText value is being validated against your <f:validateRegex pattern=".+@.+\.[a-zA-Z]+" /> and if its value not valid you getting the error , so you need to improve your regex so it will match your pattern or accept empty string...

    So wrapping it with () and adding a ? should do the job

    Try

    <f:validateRegex pattern="(.+@.+\.[a-zA-Z]+)?"/>