jquery深入(二)
jquery-validation细节
汉化
导入messages_zh.js即可
自定义提交事件
与rules和messages同级,再编写一个submitHandler:
$("#form").validate({
rules: {...},
messages: {...},
submitHandler: function() {
// 返回值为true,代表允许提交
// 返回值为false,代表拒绝提交
// 如果没有任何返回,代表拒绝提交
}
})
自定义校验规则
- 定义规则
$.validator.addMethod("cellphone", function(value, element, param) {
// 返回值为布尔类型
// true代表校验通过
// false代表校验失败
let cellphoneExp = /^1[3-9][0-9]{9}$/;
return cellphoneExp.test(value);
});
- 使用规则
$("#form").validate({
rules: {
mobile: "cellphone"
},
messages: {
mobile: "请输入合法的手机号码"
}
})
整体代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../js/jquery-3.6.0.min.js"></script>
<script src="../js/jquery.validate.js"></script>
<script src="../js/messages_zh.js"></script>
<script>
$.validator.addMethod("cellphone", function(value, element, param) {
// 返回值为布尔类型
// true代表校验通过
// false代表校验失败
let cellphoneExp = /^1[3-9][0-9]{9}$/;
return cellphoneExp.test(value);
});
$(function() {
$("#formId").validate({
rules: {
username: "required",
password: {
required: true,
number: true
},
repassword: {
required: true,
equalTo: "[name=password]"
},
zuixiaozhi: {
min: 15
},
shuzhiqujian: {
// min: 10,
// max: 20
range: [15, 20]
},
gender: "required",
mobile: "cellphone"
},
messages: {
username: "用户名必填",
password: {
required: "密码必填",
number: "必须是一个合法的数字"
},
repassword: "重复必填,并且与密码一致",
zuixiaozhi: "最小值为{0}",
shuzhiqujian: "数值必须在{0}和{1}之间",
gender: "性别必填",
mobile: "手机号不合法"
},
submitHandler: function() {
console.log("form submit...");
return true;
}
})
});
</script>
</head>
<body>
<form id="formId" action="">
必填:<input type="text" name="username"/> <br/>
必填数字:<input type="text" name="password"/> <br/>
必填重复:<input type="text" name="repassword"/> <br/>
最小值:<input type="text" name="zuixiaozhi"/> <br/>
区间:<input type="text" name="shuzhiqujian"/> <br/>
性别:<input type="radio" name="gender"/>男
<input type="radio" name="gender"/>女
<label id="gender-error" class="error" for="gender"></label>
<br/>
手机号码: <input name="mobile"><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
bootstrap
https://v3.bootcss.com