文章转载自:http://blog.csdn.net/symgdwyh/article/details/4328511
1、标准验证器
在<h:inputText/>和<h:inputSecret/>标签中加上required属性,如果为true表示是必需的,不能为空;我们也可以添加子标签<f:validateLength/>来限制字符的长度,minimum表示最小长度,maximum表示最大长度。具体写法如下:
- <h:inputText value="#{user.userName}" required="true" />
- <br>
- <h:inputSecret value="#{user.password}" required="true">
- <f:validateLength minimum="5" maximum="10"/>
- </h:inputSecret>
用标签<h:messages layout="table" style="color:red"></h:messages>来显示所有信息,layout="table"表示信息以table(HTML table)形式显示,还有一种是layout="list"表示信息以list(HTML list)方式显示。截图如下:
2、自定义验证器
①写一个类实现javax.faces.validator.Validator接口,实现方法validate(FacesContext context, UIComponent component, Object obj):
- package com.king.jsf.validator;
- import javax.faces.application.FacesMessage;
- import javax.faces.component.UIComponent;
- import javax.faces.context.FacesContext;
- import javax.faces.validator.Validator;
- import javax.faces.validator.ValidatorException;
- public class PasswordValidator implements Validator {
- @Override
- public void validate(FacesContext context, UIComponent component, Object obj) throws ValidatorException {
- String password = (String)obj;
- if(password.length() < 5 || password.length() > 10){
- FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "密码长度应该大于等于5,小于等于10。", "密码长度错误。");
- throw new ValidatorException(message);
- }
- }
- }
②在faces-config.xml文件中添加validator的配置:
- <faces-config>
- ...
- <validator>
- <validator-id>passwordValidator</validator-id>
- <validator-class>com.king.jsf.validator.PasswordValidator</validator-class>
- </validator>
- ...
- </faces-config>
③在jsp页面中使用validator:
- <h:inputSecret id="password" value="#{user.password}" required="true">
- <f:validator validatorId="passwordValidator"/>
- </h:inputSecret>
3、让Bean自动验证,在需要验证的Bean中添加validate方法,该方法没有返回值,接受FacesContext、UIComponent、Object三个参数:
- package com.king.jsf.bean;
- import java.util.Date;
- import javax.faces.application.FacesMessage;
- import javax.faces.component.UIComponent;
- import javax.faces.context.FacesContext;
- import javax.faces.validator.ValidatorException;
- public class UserBean {
- ......
- public void validate(FacesContext context, UIComponent component, Object obj) throws ValidatorException{
- String userName = (String)obj;
- if(userName.length() != 5){
- FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "用户名的长度为5个字符。","用户名错误!");
- throw new ValidatorException(message);
- }
- }
- ......
- }
在页面中如下使用验证器:
- <h:inputText value="#{user.userName}" required="true" validator="#{user.validate}" />