JSF 验证正则表达式示例

2018-02-21 10:01 更新

JSF教程 - JSF验证正则表达式示例


f:validateRegex标记用于将字符串值验证为必需的格式。

以下代码显示如何使用f:validateRegex标记。

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

标签属性

属性描述
pattern格式化模式

例子

以下代码来自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>

下面的代码来自UserBean.java。

package cn.w3cschool.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;
  }
  
}

以下代码来自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>
下载 Validate_regular_expression.zip

运行

将生成的WAR文件从目标文件夹复制到Tomcat部署文件夹,并运行Tomcat-Install-folder/bin/startup.bat。

Tomcat完成启动后,在浏览器地址栏中键入以下URL。

http://localhost:8080/simple-webapp/demo.xhtml
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号