Java – How to throw different messages when validating length and regular expression for a input text in jsf

javajsf-2validationxhtml

I have some code like this in my xhtml page

 <h:inputText    id="cardNumber"  
                 value="#{bean.cardNumber}" required="true" 
                 requiredMessage="Card Number Cannot be Blank" 
                 validatorMessage="Card Number must be 16 digits" 
                 maxlength="16" size="16" >   
        <f:validateLength  maximum="16" minimum="16" />   
        <f:validateRegex pattern="[0-9]*" for="cardNumber"/>
  </h:inputText>

For the above input text I am doing all three kinds of validation i.e required field validation,length validation,regular expression validation.

I understand that being I defined validatorMessage for </h:inputText>to validate <f:validateLength/> and <f:validateRegex/>,it throws the same message.How can I throw two different messages for <f:validateLength/>and <f:validateRegex/> ?

Best Answer

You need to modify the Messages.properties file

Add the following entries and modify them...

javax.faces.validator.LengthValidator.MAXIMUM = {1}: Validation Error: Length is greater than allowable maximum of ''{0}''
javax.faces.validator.LengthValidator.MINIMUM = {1}: Validation Error: Length is less than allowable minimum of ''{0}''

and

javax.faces.validator.RegexValidator.NOT_MATCHED = {1}: Validation Error: Value not according to pattern ''{0}''
javax.faces.validator.RegexValidator.PATTERN_NOT_SET = A pattern must be set for validate.
javax.faces.validator.RegexValidator.MATCH_EXCEPTION = The pattern is not a valid regular expression.

For a complete tutorial take a look at this : Customize Validation Error Message In JSF 2.0

And here a complete Reference to all available message that you can override in JSF 2.0.x

Related Topic