当前位置: 首页 > 工具软件 > jQuery cForm > 使用案例 >

jQuery – jQuery Validate Ajax

韶宏邈
2023-12-01

【LJ?Dragon】鱼对水说你看不到我的眼泪,因为我在水里。水说我能感觉到你的眼泪,因为你在我心里。
【LJ?Dragon】You’re more than a shadow, I’ve just to believe.
【LJ?Dragon】A true friend is some one who reaches for your hand and touches your heart.

jquery.validate ajax方式验证

<script type="text/javascript">
    $(function () {
        $("#form1").validate({
            rules: {
                pwd: {
                    required: true,
                    remote: {
                        url: "@Url.Action("ValidatePwd", "UserInfo")",
                        type: "post",
                        dataType: "json",
                        data: {
                            pwd: function () {
                                return $("#pwd").val();    //这个是取要验证的密码
                            }
                        },
                        dataFilter: function (data) {    //判断控制器返回的内容
                            if (data == "true") {
                                return true;
                            }
                            else {
                                return false;
                            }
                        }
                    }
                },
                password: {
                    required: true,
                    rangelength: [6, 16]
                },
                confirm_password: {
                    required: true,
                    rangelength: [6, 16],
                    equalTo: "#password"
                }
            },
            messages: {
                pwd: {
                    required: "请填写原始密码!",
                    remote: "原始密码不正确,请重新填写!"    //这个地方如果不写的话,是自带的提示内容,加上就是这个内容。
                },
                password: {
                    required: "请填写新密码",
                    minlength: jQuery.format("登录名长度在6-12位之间!")
                },
                confirm_password: {
                    required: "请填写确认密码!",
                    minlength: "密码需由6-16个字符(数字、字母、下划线)组成!",
                    equalTo: "两次输入密码不一致!"
                }
            },
            onfocus: true,    
            onkeyup: false,    //这个地方要注意,修改去控制器验证的事件。
            onsubmit: false
        });

 

2.案例

<script>

$().ready(function() {
  $("#cForm").validate({
  onsubmit:true,// 是否在提交是验证
  onfocusout:false,// 是否在获取焦点时验证
  onkeyup :false,// 是否在敲击键盘时验证

rules: {    //规则
  user: {  //要对应相对应的input中的name属性
    required: true
  },
  password: {
    required: true
  }
},
messages:{    //验证错误信息
  user: {
    required: "请输入用户名"
    },
  password: {
    required: "请输入密码"
  }
},
submitHandler: function(form) { //通过之后回调
//进行ajax传值
$.ajax({
  url : "{:U('user/index')}",
  type : "post",
  dataType : "json",
  data: {
    user: $("#user").val(),
    password: $("#password").val() 
  },
  success : function(msg) {
    //要执行的代码
  }
});
},
invalidHandler: function(form, validator) {return false;}
}); 
});

</script>

 

2.1 使用

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>

菜鸟教程:http://www.runoob.com/jquery/jquery-plugin-validate.html

$().ready(function() {
// 在键盘按下并释放及提交后验证提交表单
  $("#signupForm").validate({
    rules: {
      firstname: "required",
      lastname: "required",
      username: {
        required: true,
        minlength: 2
      },
      password: {
        required: true,
        minlength: 5
      },
      confirm_password: {
        required: true,
        minlength: 5,
        equalTo: "#password"
      },
      email: {
        required: true,
        email: true
      },
      topic: {
        required: "#newsletter:checked",
        minlength: 2
      },
      agree: "required"
    },
    messages: {
      firstname: "请输入您的名字",
      lastname: "请输入您的姓氏",
      username: {
        required: "请输入用户名",
        minlength: "用户名必需由两个字母组成"
      },
      password: {
        required: "请输入密码",
        minlength: "密码长度不能小于 5 个字母"
      },
      confirm_password: {
        required: "请输入密码",
        minlength: "密码长度不能小于 5 个字母",
        equalTo: "两次密码输入不一致"
      },
      email: "请输入一个正确的邮箱",
      agree: "请接受我们的声明",
      topic: "请选择两个主题"
    }
});

校验规则中的名字必须与input中的name值对应

 

3. 常用方法及注意问题

3.1我们可以用其他方式替代默认的 submit

$().ready(function() {
 $("#signupForm").validate({


        submitHandler:function(form){  //表单提交后要执行的内容
            form.submit();
        }    
    });
});

使用ajax

$(".selector").validate({     
 submitHandler: function(form) 
   {      
      $(form).ajaxSubmit();     
   }  
 })

3.2debug,只验证不提交表单

$().ready(function() {
 $("#signupForm").validate({
        debug:true
    });
});
如果一个页面中有多个表单都想设置成为 debug,则使用:
$.validator.setDefaults({
   debug: true
})

3.3ignore:忽略某些元素不验证

ignore: ".ignore"

3.4更改错误信息显示的位置

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

3.5更改错误信息显示的样式

设置错误提示的样式,可以增加图标显示,在该系统中已经建立了一个 validation.css,专门用于维护校验文件的样式
input.error { border: 1px solid red; }
label.error {
  background:url("./demo/images/unchecked.gif") no-repeat 0px 0px;

  padding-left: 16px;

  padding-bottom: 2px;

  font-weight: bold;

  color: #EA5200;
}
label.checked {
  background:url("./demo/images/checked.gif") no-repeat 0px 0px;
}

3.6每个字段验证通过执行函数

success: function(label) {
    // set   as text for IE
    label.html(" ").addClass("checked");
    //label.addClass("valid").text("Ok!")
}

3.7验证的触发方式修改

重置表单 很实用

$().ready(function() {
 var validator = $("#signupForm").validate({
        submitHandler:function(form){
            alert("submitted");   
            form.submit();
        }    
    });
    $("#reset").click(function() {
        validator.resetForm();
    });

});

3.8异步验证

remote: {
    url: "check-email.php",     //后台处理程序
    type: "post",               //数据发送方式
    dataType: "json",           //接受数据格式   
    data: {                     //要传递的数据
        username: function() {
            return $("#username").val();
        }
    }
}

3.9添加自定义校验

addMethod:name, method, message
// 中文字两个字节
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
    var length = value.length;
    for(var i = 0; i < value.length; i++){
        if(value.charCodeAt(i) > 127){
            length++;
        }
    }
  return this.optional(element) || ( length >= param[0] && length <= param[1] );   
}, $.validator.format("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)"));

// 邮政编码验证   
jQuery.validator.addMethod("isZipCode", function(value, element) {   
    var tel = /^[0-9]{6}$/;
    return this.optional(element) || (tel.test(value));
}, "请正确填写您的邮政编码");

3.10radio 和 checkbox、select 的验证

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Validate radio(单选按钮)、checkbox(复选按钮)和 select(下拉框)</title>

<link rel="stylesheet" media="screen" href="http://static.runoob.com/assets/jquery-validation-1.14.0/demo/css/screen.css">
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>

<style>
.block { display: block; }
form.cmxform label.error { display: none; }
</style>

</head>
<body>

<div id="main">

<form class="cmxform" id="form1" method="get" action="">
    <fieldset>
        <legend>通过 radio(单选按钮)和 checkbox(复选按钮)验证表单</legend>
        <fieldset>
            <legend>性别</legend>
            <label for="gender_male">
                <input  type="radio" id="gender_male" value="m" name="gender" required>
                男性
            </label>
            <label for="gender_female">
                <input  type="radio" id="gender_female" value="f" name="gender">
                女性
            </label>
            <label for="gender" class="error">请选择您的性别。</label>
        </fieldset>
        <fieldset>
            <legend>婚姻状况</legend>
            <label for="family_single">
                <input  type="radio" id="family_single" value="s" name="family" required>
                单身
            </label>
            <label for="family_married">
                <input  type="radio" id="family_married" value="m" name="family">
                已婚
            </label>
            <label for="family_other">
                <input  type="radio" id="family_other" value="o" name="family">
                其他
            </label>
            <label for="family" class="error">您选择您的婚姻状况。</label>
        </fieldset>
        <p>
            <label for="agree">请同意我们的条款</label>
            <input type="checkbox" class="checkbox" id="agree" name="agree" required>
            <br>
            <label for="agree" class="error block">请同意我们的条款!</label>
        </p>
        <fieldset>
            <legend>垃圾邮件</legend>
            <label for="spam_email">
                <input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" required minlength="2">
                垃圾邮件 - E-Mail
            </label>
            <label for="spam_phone">
                <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]">
                垃圾邮件 - Phone
            </label>
            <label for="spam_mail">
                <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]">
                垃圾邮件 - Mail
            </label>
            <label for="spam[]" class="error">请选择至少两种类型的垃圾邮件。</label>
        </fieldset>
        <p>
            <input class="submit" type="submit" value="提交">
        </p>
    </fieldset>
</form>

<form id="selecttest">
    <h2>一些关于 select 的测试</h2>
    <p>
        <label for="jungle">请选择一个丛林名词</label><br>
        <select id="jungle" name="jungle" title="请选择一个丛林名词!" required>
            <option value=""></option>
            <option value="1">Buga</option>
            <option value="2">Baga</option>
            <option value="3">Oi</option>
        </select>
    </p>

    <p>
        <label for="fruit">请选择至少两种水果</label><br>
        <select id="fruit" name="fruit" title="请选择至少两种水果!" required minlength="2" multiple="multiple">
            <option value="b">Banana</option>
            <option value="a">Apple</option>
            <option value="p">Peach</option>
            <option value="t">Turtle</option>
        </select>
    </p>

    <p>
        <label for="vegetables">请选择不超过两种蔬菜</label><br>
        <select id="vegetables" name="vegetables" title="请选择不超过两种蔬菜!" required maxlength="2" multiple="multiple">
            <option value="p">Potato</option>
            <option value="t">Tomato</option>
            <option value="s">Salad</option>
        </select>
    </p>

    <p>
        <label for="cars">请选择至少两种但不超过三种汽车</label><br>
        <select id="cars" name="cars" title="请选择至少两种但不超过三种汽车!" required rangelength="[2,3]" multiple="multiple">
            <option value="m_sl">Mercedes SL</option>
            <option value="o_c">Opel Corsa</option>
            <option value="vw_p">VW Polo</option>
            <option value="t_s">Titanic Skoda</option>
        </select>
    </p>

    <p><input type="submit" value="Validate Select 测试"></p>
</form>

</div>


</body>
</html>
 
<script>
$.validator.setDefaults({
    submitHandler: function() {
        alert("submitted!");
    }
});

$(document).ready(function() {
    $("#form1").validate();
    $("#selecttest").validate();
});
</script>

 

Reference:

【….】http://www.cnblogs.com/jingmin/p/6294982.html

 
 
 
 
 
 

转载于:https://www.cnblogs.com/anstoner/p/6538033.html

 类似资料: