Kunal Jaggi
User input validation is an important part of any Web application's navigation flow. There are two peculiar tasks that every Web application performs-check that all required form fields are filled in and in case of any malformed or erroneous data from the user, redisplay the form with proper error messages.
Using vanilla servlets and JSP pages to counter malformed user input can be cumbersome and difficult to maintain. On the other hand is JSF that provides a standard conversion, validation, and messaging framework to validate user input. In this article, we'll go the JSF way and roll out a JSF framework-based custom validator.
| Direct Hit! |
Applies To: Java EE developers
USP: Roll custom validators in JSF Web applications
Primary Link: http://java.sun.com/javaee/javaserverfaces/
Google Keywords: JSF validations
On CD: PCQ Professionalsystem\labs |
|
JSF validation approaches
JSF offers rich support for validating user input. Broadly, JSF supports automatic and custom validations. For example, to enable length validation for an HTML input text, f:validateLength should be added as a child to h:inputText tag. Further, you can also validate via automatic 'type conversion'. JSF's type conversion is very similar to JavaBean's <jsp:setProperty> tag, the bean properties are defined with primitive types such as int, short, long, etc. In case, there's a conversion error, form is redisplayed. You can also add the required attribute to any input element to indicate that empty values are errors.
For trivial applications, automatic JSF conversion and validation is sufficient to validate user input. Further, you can roll custom validation techniques for more demanding scenarios. JSF also provides nifty procedures to avoid displaying verbose messages by changing the default validator messages.
Using custom validator
With a custom validator, we can make sure that the user input is correct and any malformed data entered by the user results in redisplaying the form. As an
illustration, we'll roll a simple newsletter subscription application wherein we'll ask the user to enter her first name, last name and e-mail address.