JavaServer Faces 1.x does not explicitly support client-side validation and only provides a minimal set of server-side validators. On the other hand, Apache Commons Validator supports both client- and server-side validators and comes with the following useful validators:
Client side Validate demo:
Shale provides three JSP tags that let you use the Commons Validator: val:commonsValidator
, val:validatorVar
, and val:validatorScript
. The first two lets you attach a commons validator to a JSF input component and the third generates JavaScript validation code for validating each JSF component that has one or more Commons validators in a particular form. You can attach as many Commons validators to a single JSF input component as you wish.
Here's what you need to do to use Shale validation:
onsubmit
attribute to your h:form
tag that calls the JavaScript validation function generated by val:validatorScript
. val:commonsValidator
and, optionally, val:validatorVar
. val:validatorScript
tag at the end of the h:form
tag's body. Here's an example:
In the preceding example, we've attached three Commons validators to a single JSF input component. To pass validation, the field must have a value that starts with a number between 4 and 6 inclusive and that value must be a valid credit card number as verified by the Luhn algorithm. Two of the validations are performed on both client and server and one is performed on the server only.
Note: At the present time, you have the option to forego server-side validation, which is considered very bad practice. Users can turn off JavaScript, so you should always backup client-side validation with server-side validation. In the future, Shale may enforce server-side validation if it's not explicitly specified.