f:validateLength” is a JSF string length validator tag, which is used to check the length of a string. For example,

<h:inputText id="username" value="#{user.username}">
	<f:validateLength minimum="5" maximum="10" />
</h:inputText>

When this form is submitted, the validator will make sure the “username” text field contains a minimum length of 5, maximum length of 10.

“f:validateLength” example

A JSF 2.0 example to show the use of “f:validateLength” tag to validate the length of a “username” text field, when the validator failed, display the error message via “h:message” tag.

1. Managed Bean

A dummy managed bean to hold the “username” property only.

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 username;
 
	public String getUsername() {
		return username;
	}
 
	public void setUsername(String username) {
		this.username = username;
	}
 
}

2. JSF Page

JSF XHTML page, show the use of “f:validateLength” tag to make sure the form’s input “username” contains a minimum length of 5, maximum length of 10.

<?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"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      >
    <h:body>
 
    	<h1>JSF 2 validateLength example</h1>
 
	<h:form>
 
		<h:panelGrid columns="3">
 
			Enter UserName : 
 
			<h:inputText id="username" value="#{user.username}" 
				size="20" required="true"
				label="UserName" >
				<f:validateLength minimum="5" maximum="10" />
			</h:inputText>
 
			<h:message for="username" style="color:red" />
 
		</h:panelGrid>
 
		<h:commandButton value="Submit" action="result" />
 
	</h:form>	
    </h:body>
</html>

3. Demo

Minimum length validation failed.

jsf2-ValidateLength-Example-1

Maximum length validation failed.

jsf2-ValidateLength-Example-2

Download Source Code

Download It – JSF-2-ValidateLength-Example.zip (9KB)

Reference

  1. JSF 2 validateLength JavaDoc
Note : You can find more similar articles at - JSF 2 Tutorials