JSF Tutorial - JSF Validate regular expression Example








f:validateRegex tag is used to validate a string value to a required format.

The following code shows how to use the f:validateRegex tag.

<f:validateRegex pattern="((?=.*[a-z]).{6,})" />

Tag Attributes

AttributeDescription
patternFormatting pattern

Example

The following code is from result.xhtml.

<?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>
    <h:panelGrid columns="2">
    Password :  <h:outputText value="#{user.password}" />
    </h:panelGrid>
    </h:body>
</html>

The following code is from UserBean.java.

package com.java2s.common;

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;

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }
  
}

The following code is from demo.xhtml.

<?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>
    <h:form>
      <h:panelGrid columns="3">
        Enter your password : 
        <h:inputSecret id="password" value="#{user.password}" 
          size="20" required="true"
          label="Password">
          <f:validateRegex pattern="\d\d\d\d" />
        </h:inputSecret>
        <h:message for="password" style="color:red" />
      </h:panelGrid>
      <h:commandButton value="Submit" action="result" />
    </h:form>
    </h:body>
</html>


Download Validate_regular_expression.zip





To RUN

Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.

After Tomcat finish starting, type the following URL in the browser address bar.

http://localhost:8080/simple-webapp/demo.xhtml