“ f:validateRequired ”是JSF 2.0中的新验证器标记,用于确保输入字段不为空。 例如,
<h:inputSecret id="password" value="#{user.password}">
<f:validateRequired />
</h:inputSecret>
另外,您也可以使用“ required”属性,两者都执行相同的空值验证。
<h:inputSecret id="password" value="#{user.password}" required="true" />
“ f:validateRequired”示例
一个JSF 2.0示例,显示了使用“ f:validateRequired ”标记来确保“ password”字段不为空。
1.托管豆
用户管理的bean。
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 password;
String confPassword;
//getter and setter methods
}
2. JSF页面
在JSF XHTML页面上,显示“ f:validateRequired ”标记的使用,以确保“ password”和“ confirm password”字段都不为空。
<?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>
<h1>JSF 2 validateRequired example</h1>
<h:form>
<h:panelGrid columns="3">
Enter your password :
<h:inputSecret id="password" value="#{user.password}"
size="20" required="true"
label="Password" />
<h:message for="password" style="color:red" />
Enter your password again :
<h:inputSecret id="confPassword" value="#{user.confPassword}"
size="20" label="Confirm Password">
<f:validateRequired />
</h:inputSecret>
<h:message for="confPassword" style="color:red" />
</h:panelGrid>
<h:commandButton value="Submit" action="result" />
</h:form>
</h:body>
</html>
3.演示
如果“密码”或“确认密码”字段为空,则显示错误消息。
下载源代码
下载它– JSF-2-ValidateRequired-Example.zip (9KB)
参考
翻译自: https://mkyong.com/jsf2/jsf-2-validaterequired-example/