In the previous blog entry titled "Writing your own validator" you learned how to write a validator and hook it up for validation. At that time we made it all work using the faces-config.xml file. There is however another way, which we will describe below!
Since JSF 2 it is also possible to use BeanValidation as specified in JSR 303. The following blog article describes how this JSR has been integrated within JSF 2.
With the following JSF managed bean.
Writing your own validator is a straightforward process. It involves implementing the Validator API and making sure you register it properly.
Say you want to write a validator that will not allow you to use the string "Hello World" as a value.
Say you want to make sure that a value is required.
If you want to validate input against a regular expression then you would use the RegexValidator.
Say you want to make sure only letters are used for a name.
Just like the LongRangeValidator before the DoubleRangeValidator validates if the given value is within the given range, but then a range of doubles.
Say you want to make sure your donors can donate as little as 1.00 but at most 250.00.
If you want to make sure a value is within given Long range then the LongRangeValidator is for you!
Say you want to make sure your users are at least 13 but at most 18.
The LengthValidator is one of the standard validators that is specified by the JavaServerFaces specification. It allows you to verify (validate) if the proposed input (submitted value) on a given component is valid.
The definition of a Validator according to the Validator interface:
void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
The Faces Context is passed in so the validator can introspect various aspects of the request and response.
During the JSF lifecycle each input value can be validated. As such the JSF runtime allows you to write validators that will take care of that during request processing.