<f:validateLength>
标签用于验证字符串值的长度。我们可以使用<f:validateLength>
标签,如下所示。
<f:validateLength minimum="5" maximum="8" />
打开 NetBeans IDE 创建一个Web工程:ValidateStringLength,其目录结构如下所示 -
创建以下文件代码,文件:index.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: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>
文件: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> UserName : <h:outputText value="#{user.username}" /> </h:body> </html>
文件:User.java 的代码内容如下所示 -
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.zyiz; /** * * @author Administrator */ import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "user") @SessionScoped public class User implements Serializable { String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
右键运行工程:ValidateStringLength,如果没有任何错误,打开浏览器访问:
http://localhost:8084/ValidateStringLength/
应该会看到以下结果 -
简单写入一些信息(超过10个字符),然后提交 -