jsf 表单验证

<?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" validator="#{user.validate}"
					label="Password" />
				
				<h:message for="password" style="color:red" />
			
				Enter your password again : 
				
				<h:inputSecret id="confPassword" value="#{user.confPassword}" 
					size="20" required="true" validator="#{user.validate}"
					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>

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

@ManagedBean(name = "user")
@SessionScoped
public class UserBean {
	String password;
	String confPassword;

	public String getPassword() {
		return password;
	}

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

	public String getConfPassword() {
		return confPassword;
	}

	public void setConfPassword(String confPassword) {
		this.confPassword = confPassword;
	}

	public void validate(FacesContext context, UIComponent component, Object obj)
			throws ValidatorException {
		String password = (String) obj;

		if (password.length() < 6) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "字符长度小于6", "字符长度不得小于6");
			throw new ValidatorException(message);
		}
		if (!password.matches(".+[0-9]+")) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "密码必须包括字符与数字", "密码必须是字符加数字所组成");
			throw new ValidatorException(message);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值