代码如下:
Field.prototype.set_callback=function(val){
var self=this; //换一个名字来存储this,不然函数的闭包中会覆盖这个名字
val.on_suc=function(){ //验证成功执行的方法
self.checked=true; //将字段设置为验证成功
self.on_suc(val.tips); //执行验证成功的事件
}
val.on_error=function(){ //验证失败的时候执行的方法
self.checked=false; //字段设置为验证失败
self.on_error(val.tips);//执行验证失败的事件
}
}
接下来我们就来看看验证器,验证器是真正执行验证过程的类,根据一般的验证过程,我们
可以将其分类成,长度验证(包括必填验证),正则表达式验证,自定义函数验证,Ajax远
程验证这几种,所以我们定义这几种验证器类,Ajax远程验证为了方便引用了jQuery,其他
部分也有用到:
代码如下: 代码如下: 最后用一个例子来看看怎么用: 代码如下:
//长度验证的验证器类
function Len_val(min_l,max_l,tip){
this.min_v=min_l;
this.max_v=max_l;
this.tips=tip;
this.on_suc=null;
this.on_error=null;
}
Len_val.prototype.validate=function(fd){
if(fd.length
this.on_error();
return false;
}
this.on_suc();
return true;
}
//正则表达式验证器
function Exp_val(expresion,tip){
this.exps=expresion;
this.tips=tip;
this.on_suc=null;
this.on_error=null;
}
Exp_val.prototype.validate=function(fd){
if(!fd){
this.on_suc();
return true;
}
if(this.exps.test(fd)){
this.on_suc();
return true;
}else{
this.on_error();
return false;
}
}
//远程验证器
function Remote_val(url,tip){
this.p_url=url;
this.tips=tip;
this.on_suc=null;
this.on_error=null;
}
Remote_val.prototype.validate=function(fd){
var self=this;
$.post(this.p_url,{f:fd},
function(data){
if(data.rs){
self.on_suc();
return;
}else{
self.on_error();
}
},"json"
);
return false;
}
//自定义函数验证器
function Man_val(tip,func){
this.tips=tip;
this.val_func=func;
this.on_suc=null;
this.on_error=null;
}
Man_val.prototype.validate=function(fd){
if(this.val_func(fd)){
this.on_suc();
}else{
this.on_error();
}
}
最后我们用一个userform的类来做一个入口,在构造的时候传入Field对象的列表,并且将
每一个控件的onblur事件绑定到validate的包装器上
function UserForm(items){
this.f_item=items; //把字段验证对象数组复制给属性
for(idx=0;idx
$("#"+this.f_item[idx].field_id).blur(fc); //绑定到控件上
}
}
//绑定验证事件的处理器,为了避开循环对闭包的影响
UserForm.prototype.get_check=function(v){
return function(){ //返回包装了调用validate方法的事件
v.validate();
}
}
接下来需要定义一个方法来绑定提交按钮的onclick事件:
代码如下:
//绑定提交事件到元件
UserForm.prototype.set_submit=function(bid,bind){
var self=this;
$("#"+bid).click(
function(){
if(self.validate()){
bind();
}
}
);
}
这里提到了一个UserForm的validate方法,如下:
代码如下:
//验证所有的字段
UserForm.prototype.validate=function(){
for(idx in this.f_item){ //循环每一个验证器
this.f_item[idx].validate(); //再检测一遍
if(!this.f_item[idx].checked){
return false; //如果错误就返回失败,阻止提交
}
}
return true; //一个都没错就返回成功执行提交
}