jQuery Validate插件使用

jQuery Validate 插件为表单提供了强大的验证功能

其中

1、替代submit

 $("#user_form").validate({
        submitHandler:function(form){
            alert("这里提交!");   
            form.submit();
        }    
    });
使用 ajax 方式
 $("#user_form").validate({     
 submitHandler: function(form) 
   {      
      $(form).ajaxSubmit();     
   }  
 }) 
提交表单, 需要使用 form.submit(),而不要使用 $(form).submit()

2、更改错误信息显示的位置

errorPlacement:Callback
指明错误放置的位置,默认情况是:error.appendTo(element.parent());即把错误信息放在验证的元素后面
errorPlacement: function(error, element) {  
    error.appendTo(element.parent());  
}

3、异步验证验证,eg:验证注册手机号是否重复,用户名是否可用?等

remote:URL
使用ajax方式验证,默认会提交当前验证的值到远程地址,如果需要提交其他的值,可以使用 data 选项。
remote: "check_phone.php"
remote: {
    url: "check_phone.php",     //后台处理程序
    type: "post",               //数据发送方式
    dataType: "json",           //接受数据格式   
    data: {                     //要传递的数据
        user_phone: function() {
            return $("#user_phone").val();
        }
    }
}
远程地址只能输出 "true" 或 "false",不能有其他输出。

4、添加自定义验证,eg,添加正则表达式,

// 手机号码验证
jQuery.validator.addMethod("isMobile", function(value, element) {
  var length = value.length;
  var mobile = /^13[0-9]{1}[0-9]{8}$|15[012356789]{1}[0-9]{8}$|14[57]{1}[0-9]{8}$|17[678]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$/;
  return this.optional(element) || (length == 11 && mobile.test(value));
}, "请正确填写您的手机号码");

5、来个完整的例子

 $('#user_form').validate({
   submitHandler:function(form){
      ajaxpost('user_form', '', '', 'onerror');
    },
    rules : {
      password: {
        maxlength: 20,
        minlength: 6
      },
    mobile   : {
       required : true,
       isMobile : true,
       remote   : {
       url :'<?php echo urlLifeShop('employee_mgr','ajax',array('branch'=>'check_phone'));?>',
       type:'get',
       data:{
       phone : function(){
          return $('#mobile').val();
               }
             }
          }
       }
  },
  messages : {
     password : {
     maxlength: '<i class="fa fa-exclamation-circle"></i><?php echo '检查密码长度';?>',
     minlength: '<i class="fa fa-exclamation-circle"></i><?php echo '检查密码长度';?>'
    },
  mobile  : {
      required : '<i class="fa fa-exclamation-circle"></i><?php echo '请填写手机号';?>',
      isMobile : '<i class="fa fa-exclamation-circle"></i><?php echo '手机号格式错误';?>',
      remote : '<i class="fa fa-exclamation-circle"></i><?php echo '该手机号已经被注册!';?>'
           }
      }
});

原创文章,转载请注明: 转载自HSBLOG

本文链接地址: jQuery Validate插件使用