Hey guys in this example, we will discuss adding validation and customizing the validation messages in JSF with Example
Table of Contents
Overview
- To create textbox we use
<h:inputText>
tag - We will add the attribute
required
totrue
- We will add the attribute
requiredMessage
for custom validation message - To validate
minimum
andmaximum
characters we will use<c:validateLength>
tag - We will use
<h:message>
tag to display the error messages
Complete example
We will create this example step by step, follow this tutorial till the end
Read More:
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Complete Spring Data JPA Tutorial
- Check the Complete Spring Security Tutorial
- Check the Javascript Projects for Beginners
Create Dynamic Web Project
To create a dynamic web project, you can read the following tutorial
Create a bean
Create Register.java
file inside the in.bushansirgur.jsf.beans
package and add the following content
package in.bushansirgur.jsf.beans;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class Register {
private String email;
private String name;
public Register() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Create Input form
Create register-form.xhtml
file inside the WebContent and add the following content
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:c="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Input Form</title>
<style>
.error {
color: red;
font-style: italic;
}
</style>
</h:head>
<h:body>
<h:form>
Name: <h:inputText id="name" label="Name" value="#{register.name}">
<c:validateLength minimum="5" maximum="15" />
</h:inputText>
<h:message for="name" styleClass="error" />
<br/><br/>
Email: <h:inputText id="email" value="#{register.email}" required="true" requiredMessage="Please enter email"/>
<h:message for="email" styleClass="error" />
<br/><br/>
<h:commandButton value="Register" action="dashboard" />
</h:form>
</h:body>
</html>
Create a Response page
Create dashboard.xhtml
file inside the WebContent and add the following content
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Dashboard</title>
</h:head>
<h:body>
<div>
<span>The Logged in user is: #{register.email}</span>
</div>
<div>
<p>Your name is: #{register.name}</p>
</div>
</h:body>
</html>
Run the app
To run the application, right click on the project, select Run As -> choose Run on Server
Open the browser, navigate to the URL http://localhost:8080/JSF-hello-world/faces/register-form.xhtml
—
—
—
That’s it for this post. If you like this post, then please share this with your friends and collogues. Also share this post on your social media profiles as well.