This post demonstrates how to use individual error messages for each field validated in JSF
. Previously, we used “combined” error messages displayed in only one location on the page in
JSF – Basic Form Validation for Required Fields
For this post, we will reuse most of the stuff in that previous post. Modifying only the registration page shown Registration Page - Request
section.
Requirements
Stuff used in this post.
- JSF 2.2
- javax.faces-2.2.8.jar
- JDK 8
Registration Page – Request
Note the for
keyword in the
<h:message for=".."/> . It refers to the
<h:inputText/> ‘s id
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core"> <h:head> <title>Employee Registration Form</title> <style> .form-error {color:red} </style> </h:head> <h:body> <h:form> <!-- Commented out to use individual h:message instead <h:messages styleClass="form-error"/> --> <table> <tr> <td>First Name:</td> <td> <h:inputText id="field1" value="#{employee.firstName}" label="First Name"/> <h:message for="field1" styleClass="form-error"/> </td> </tr> <tr> <td>Last Name:</td> <td> <h:inputText id="field2" value="#{employee.lastName}" required="true" label="Last Name"/> <h:message for="field2" styleClass="form-error"/> </td> </tr> <tr> <td>Email:</td> <td> <h:inputText id="field3" value="#{employee.email}" required="true" label="Email"/> <h:message for="field3" styleClass="form-error"/> </td> </tr> </table> <h:commandButton value="Submit" action="registration_response"/> </h:form> </h:body> </html> |
Testing
The required fields are Last Name
and Email
. To test with a validation error, we’ll submit the page with only First Name
provided.