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 />
</h:inputText>
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.
<context-param>
    <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
    <param-value>true</param-value>
</context-param>

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;

@ManagedBean
@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"
        "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>
    <h2>JSF Validate Required Field example</h2>
    <h:form>
        <h:panelGrid columns="2">
            <h:outputLabel value="First Name:">
                <h:inputText label="First Name" id="firstName" value="#{userBean.firstName}">
                    <f:validateRequired />
                </h:inputText>
            </h:outputLabel>
            <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:outputLabel>
            <h:message for="lastName" style="color:red" />
        </h:panelGrid>
        <h:commandButton value="submit" action="result"/>
    </h:form>
</h:body>
</html>

Demo

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

jsf validate required field

Preferences

Download

You may also like...