分类:
2008-10-16 19:25:08
利用
jsf页面通过validatorId调用验证器(该id在faces-config.xml中配置)
view plaincopy to clipboardprint?
faces-config.xml中配置(配置调用的自定义验证器类)
view plaincopy to clipboardprint?
com.xgtimes.Validator.emailValidator类的实现:该类必须实现Validator 接口及接口抽象方法validate(),且validate()方法要求抛出ValidatorException异常,该异常以FacesMessage为参数抛出,旨在验证失败时,确定向视图发送的消息,如果验证成功则什么也不做,当然如果验证成功也要求发送消息的话,同样抛出ValidatorException异常即可。该类其实很简单,唯一要做的就是,确定在什么情况下应该抛出异常。另外,为了支持国际化,在抛出消息时,采用从资源文件com.xgtimes.CustomMessages.properties获取EMAIL_ERROR_MESSAGE键值,通过fc.getViewRoot().getLocale(),使该消息符合当前语言环境。(注:这里Email验证逻辑不完全规范)
view plaincopy to clipboardprint?
package com.xgtimes.Validator;
import java.util.ResourceBundle;
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 emailValidator implements Validator {
public void validate(FacesContext arg0, UIComponent arg1, Object arg2) throws ValidatorException {
String Value=(String)arg2;
if(!isValid(Value)){
FacesMessage message=new FacesMessage(FacesMessage.SEVERITY_ERROR,this.getMes(arg0),null);
throw new ValidatorException(message);
}
}
private boolean isValid(String value) {
boolean isvalid=true;
int index=value.indexOf("@");
if(index<=0||index>value.length()-6) {
isvalid=false;
}
return isvalid;
}
private String getMes(FacesContext fc) {
String str=null;
ResourceBundle rb=ResourceBundle.getBundle("com.xgtimes.CustomMessages", fc.getViewRoot().getLocale());
str=rb.getString("EMAIL_ERROR_MESSAGE");
return str;
}
}