IT技术博客大学习 共学习 共进步

Jquery通用表单验证类

废墟 2011-09-19 23:41:14 累计浏览 3,284 次
好吧,最近写js写的蛋疼,其实我是一枚php程序猿啊。。其实说白了,有点抄袭CI里面的表单验证类的意思,因为用法很像
/**
* 通用js验证类
* by 废墟
* http://anerg.com
*/
var Validator = {
  label:{
    'username':'帐号',
    'password':'密码',
    'passconf':'密码确认',
    'email':'Email',
    'vcode':'验证码',
    'author':'笔名',
    'truename':'真实姓名',
    'qq':'QQ',
    'idcard':'身份证号码',
    'tel':'电话',
    'zipcode':'邮编',
    'address':'联系地址'
  },
  trim:function(item) {
    this.Value = $.trim(this.Value);
    item.val(this.Value);
  },
  require:function(item) {
    if(this.Value == '') {
      this.ErrorMessage[item.attr('name')] = '这是必填项,麻烦您啦^_^';
      return false;
    } else {
      return true;
    }
  },
  min_length:function(item, len) {
    if(this.getStrActualLen(this.Value) < len) {
      this.ErrorMessage[item.attr('name')] = '太短啦。必须超过'+len+'个字符';
      return false;
    } else {
      return true;
    }
  },
  max_length:function(item, len) {
    if(this.getStrActualLen(this.Value) > len) {
      this.ErrorMessage[item.attr('name')] = '太长啦。不能超过'+len+'个字符';
      return false;
    } else {
      return true;
    }
  },
  matches:function(item, filed) {
    var v = $("input[name='"+filed+"']:visible").val();
    if(v != this.Value) {
      this.ErrorMessage[item.attr('name')] = '两次输入的'+this.label[filed]+'不一致 :(';
      return false;
    } else {
      return true;
    }
  },
  email:function(item) {
    var re = /^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    if(!re.test(this.Value)) {
      this.ErrorMessage[item.attr('name')] = "格式不正确呀,请检查一下";
      return false;
    } else {
      return true;
    }
  },
  qq:function(item) {
    var re = /^[0-9]{5,11}$/;
    if(!re.test(this.Value)) {
      this.ErrorMessage[item.attr('name')] = "格式不正确呀,请检查一下";
      return false;
    } else {
      return true;
    }
  },
  vcode:function(item) {
    var re = /^\d{4}$/;
    if(!re.test(this.Value)) {
      this.ErrorMessage[item.attr('name')] = "验证码错误";
      return false;
    } else {
      return true;
    }
  },
  idcard:function(item) {
    var re = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/;
    if(!re.test(this.Value)) {
      this.ErrorMessage[item.attr('name')] = "格式不正确呀,请检查一下";
      return false;
    } else {
      return true;
    }
  },
  checkusername:function(item) {
    var _stat = true;
    var _this = this;
    $.ajax({
      async:false,
      type:'POST',
      url:'/ajax/checkusername',
      data:"username="+this.Value,
      dataType:'text',
      success:function(rs) {
        if(rs == 1) {
          _this.ErrorMessage[item.attr('name')] = '呃,已经被别人用了';
          _stat = false;
        } else if(rs == 9) {
          _this.ErrorMessage[item.attr('name')] = '换一个吧。Sorry :(';
          _stat = false;
        } else {
          _stat = true;
        }
      }
    });
    return _stat;
  },
  userexists:function(item) {
    var _stat = true;
    var _this = this;
    $.ajax({
      async:false,
      type:'POST',
      url:'/ajax/checkusername',
      data:"username="+this.Value,
      dataType:'text',
      success:function(rs) {
        if(rs == 1 || rs == 9) {
          _stat = true;
        } else {
          _this.ErrorMessage[item.attr('name')] = '帐号不存在';
          _stat = false;
        }
      }
    });
    return _stat;
  },
  checkauthor:function(item) {
    var _stat = true;
    var _this = this;
    $.ajax({
      async:false,
      type:'POST',
      url:'/ajax/checkauthor',
      data:"author="+this.Value,
      dataType:'text',
      success:function(rs) {
        if(rs == 1) {
          _this.ErrorMessage[item.attr('name')] = '呃,已经被别人用了';
          _stat = false;
        } else if(rs == 9) {
          _this.ErrorMessage[item.attr('name')] = '换一个吧。Sorry :(';
          _stat = false;
        } else {
          _stat = true;
        }
      }
    });
    return _stat;
  },
  Items:[],
  ErrorMessage:[],
  Value:'',
  Validate:function(theItem) {
    if(typeof(theItem) != 'undefined') {
      this.Items = [];
      this.ErrorMessage = [];
      var valid = theItem.attr('valid');
      if(typeof(valid) != 'undefined') {
        this.Items[theItem.attr('name')] = theItem;
        this.Value = theItem.val();
        var method = valid.split('|');
        for(var i in method) {
          var re = /(.*)\[(.*[^\]])\]$/;
          if(re.test(method[i])) {
            var tmp = method[i].match(re);
            if(typeof(this[tmp[1]]) == 'function' && this[tmp[1]](theItem, tmp[2]) == false)
              break;
          } else {
            if(typeof(this[method[i]]) == 'function' && this[method[i]](theItem) == false)
              break;
          }
        }
        
        showNotice(this.Items, this.ErrorMessage);//显示错误或者正确提示。这个方法得自己写
        
        if(this.count(this.ErrorMessage) > 0) {
          return false;
        } else {
          return true;
        }
      }
    }
  },
  count:function(obj) {
    var counter = 0;
    for(i in obj) counter++;
    return counter;
  },
  getStrActualLen:function(sChars){
    sChars = $.trim(sChars);
    var len = 0;
    for(i=0;i<sChars.length;i++){
      iCode = sChars.charCodeAt(i);
      if((iCode>=0 && iCode<=255)||(iCode>=0xff61 && iCode<=0xff9f)){
        len += 1;
      }else{
        len += 2;
      }
    }
    return len;
  }
}


一般来说,还需要下面两个js函数,不过这俩你得根据自己需要来修改了
function showNotice(objs, msgs) {
  for(i in objs) {
    clearNotice(objs[i]);//清除提示信息
    if(typeof(msgs[i]) != 'undefined') {
      objs[i].parents('dd').addClass('wrong');
      objs[i].after('<div class="wrong_tip">'+msgs[i]+'</div>');
    } else {
      objs[i].parents('dd').addClass('correct');
      objs[i].after('<div class="ok">&nbsp;&nbsp;</div>');
    }
  }
}
function clearNotice(obj) {
  obj.parents('dd').removeClass();
  obj.parents('dd').find('.ok').remove();
  obj.parents('dd').find('.wrong_tip').remove();
}


下面呢,是html的内容,其关键就在于valid="trim|require"类似的这里了。
<dl>
  <dt>通行证账号:</dt>
  <dd>
    <input name="username" valid="trim|require|min_length[4]|max_length[14]|checkusername" type="text" class="id"/>
  </dd>
  <dd class="description">中英文均可不超过6个汉字或12个字符,不可重复。</dd>
</dl>


js的相关使用上也很简单
/* 失去焦点时提示 */
$("input").blur(function(){
  Validator.Validate($(this));
});

/* ajax提交登录信息 */
$("form[id='login']").submit(function() {
  var st = true;
  var _this = this;
  $(this).find("[valid]").each(function() {
    st = st&Validator.Validate($(this));
  })
  if(st == 1) {
    $.ajax({
      url:"/onlogin",
      type:"POST",
      data:$(this).serialize(),
      dataType:'json',
      success:function(auth) {
        onAjax(auth, _this);
      }
    });
  }
  return false;
})

建议继续学习

  1. JQuery实现Excel表格呈现 (累计阅读 48,167)
  2. 分享一个JQUERY颜色选择插件 (累计阅读 14,064)
  3. jQuery插件---轻量级的弹出窗口wBox. (累计阅读 10,627)
  4. 10个强大的Ajax jQuery文件上传程序 (累计阅读 8,726)
  5. jQuery性能优化指南 (累计阅读 8,647)
  6. jQuery的data()方法 (累计阅读 8,504)
  7. jQuery Color Animations颜色动画插件 (累计阅读 8,347)
  8. 精于图片处理的10款jQuery插件 (累计阅读 7,265)
  9. 配合jquery实现异步加载页面元素 (累计阅读 6,286)
  10. jQuery中getJSON跨域原理详解 (累计阅读 6,267)