JS表单验证组件浅讲

来源:互联网 发布:加工中心的编程分为 编辑:程序博客网 时间:2024/05/08 20:13


//验证器
Checker =function(){
 
}

//必验证项集合
Checker.items=new Array();

//获取数组的大小

Array.size=function(obj){
 return length(obj);
}

//长度验证--可由此定义常规的验证

Checker.lenCheck=function(obj,min,max,isReq,msg_info,msg_ok,msg_error){
 joinReq(obj,isReq);
 $(obj).blur(function(){
  if($(obj).val().length.trim()>=min&&$(obj).val().length.trim()<max){
   Checker.items[$(this).attr("id")]=true;
   $("#msg").html(msg_ok);
  }else{
   Checker.items[$(this).attr("id")]=false;
   $("#msg").html(msg_error);//注意此处只是引子,具体业务需要编写相应的组件
  }
 }).focus(function(){

     //加入提示功能

  });  
};

//如果必要项,加入必验证数据集

joinReq=function(obj,isReq){
 if(isReq){   
  var id=$(obj).attr("id");
  Checker.items[id]=false;

 } 
};

$(function(){
 $("#frm").submit(function(){//绑定表单提交事件
  

  //遍历确认其中是存在验证没有通过项
  var len=Array.size(Checker.items));

  var isPass=true;
  for(var o in Checker.items){

    if(!Checker.items[o]){//等于false说明该项为必验项,但可能还没有输入(没有验证),也有可能是输入后,但验证未通过项

        $(o).blur(); //触发验证

        isPass=false;

    }

 }
  return isPass;
   
 });
});


function length(obj){
 if(typeof(obj)=='string'){
  return obj.length; 
 }else if(typeof(obj)=='object'){
  var i=0;
  for(var t in obj){
   i++;
  }
  return i;
 }else{
  return 0; 
 }
}
$(function(){ 
 
 Checker.lenCheck($("#userName"),2,10,true,"用户名不能为空","OK",“ERROR”);
 Checker.lenCheck($("#password"),2,10,true,"密码不能为空","OK",“ERROR”);
 Checker.lenCheck($("#email"),2,10,true,"邮箱不能为空","OK",“ERROR”);
 
 
});



0 0
原创粉丝点击