JSF Validate Required Field Example

In this example we will show how to validate required field in JSF. When a user submits a form and you want to make sure a field has a value you can put some required field validation on that field. There are two ways you can validate an input field as required.

Using f:validateRequired

The f:validateRequired tag is added to the JSF 2 core tag library and can validate a field as required.

<h:inputText id="firstName" value="#{userBean.firstName}">
    <f:validateRequired />
Note: The downside about this validation is that it does not validate required fields by default. Say What?! You need to specify the javax.faces.VALIDATE_EMPTY_FIELDS in order to tell JSF to validate empty fields.

Using required attribute

A better and easier way to make a field required is by adding the required attribute to the field.

<h:inputText id="lastName" value="#{userBean.lastName}" required="true"/>

JSF Managed Bean

package com.memorynotfound.jsf;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

public class UserBean {

    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;

    public String getLastName() {
        return lastName;

    public void setLastName(String lastName) {
        this.lastName = lastName;

JSF Validate Required Field Page

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml"
    <h2>JSF Validate Required Field example</h2>
        <h:panelGrid columns="2">
            <h:outputLabel value="First Name:">
                <h:inputText label="First Name" id="firstName" value="#{userBean.firstName}">
                    <f:validateRequired />
            <h:message for="firstName" style="color:red" />

            <h:outputLabel value="Last Name:">
                <h:inputText label="Last Name" id="lastName" value="#{userBean.lastName}" required="true"/>
            <h:message for="lastName" style="color:red" />
        <h:commandButton value="submit" action="result"/>


URL: http://localhost:8080/jsf-validate-required/

jsf validate required field



You may also like...