JSF 2 validateRequired example
“f:validateRequired” is a new validator tag in JSF 2.0, which is used to make sure the input field is not empty. For example,
<h:inputSecret id="password" value="#{user.password}"> <f:validateRequired /> </h:inputSecret>
Alternatively, you can use the “required” attribute also, both are doing the same empty value validation.
<h:inputSecret id="password" value="#{user.password}" required="true" />“f:validateRequired” example
A JSF 2.0 example to show the use of “f:validateRequired” tag to make sure the “password” field is not empty.
1. Managed Bean
An user managed bean.
package com.mkyong; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name="user") @SessionScoped public class UserBean implements Serializable{ String password; String confPassword; //getter and setter methods }
2. JSF Page
JSF XHTML page, show the use of “f:validateRequired” tag to make sure both “password” and “confirm password” fields are not empty.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" > <h:body> <h1>JSF 2 validateRequired example</h1> <h:form> <h:panelGrid columns="3"> Enter your password : <h:inputSecret id="password" value="#{user.password}" size="20" required="true" label="Password" /> <h:message for="password" style="color:red" /> Enter your password again : <h:inputSecret id="confPassword" value="#{user.confPassword}" size="20" label="Confirm Password"> <f:validateRequired /> </h:inputSecret> <h:message for="confPassword" style="color:red" /> </h:panelGrid> <h:commandButton value="Submit" action="result" /> </h:form> </h:body> </html>
3. Demo
If “password” or “confirm password” fields are empty, display the error message.








won’t work as expected!!!
h:inputSecret tag in the sample source code cotains ‘required’ attribute that should not exist