表单验证(jQuery Validate)
jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求。该插件捆绑了一套有用的验证方法,包括 URL 和电子邮件验证,同时提供了一个用来编写用户自定义方法的 API。所有的捆绑方法默认使用英语作为错误信息,且已翻译成其他 37 种语言。
官网:http://jqueryvalidation.org/。
应用实例:http://runoob.com/jquery/jquery-plugin-validate.html
官方文档:https://jqueryvalidation.org/documentation/
规则
required: [true, 'msg'] | 必填字段 |
---|---|
number: [true, 'msg'] | 必须为数字 |
digits: [true, 'msg'] | 必须为整数 |
email: [true, 'msg'] | 必须为正确格式的邮箱 |
url: [true, 'msg'] | 必须为正确格式的网址 |
date: [true, 'msg'] | 必须为正确格式的日期 |
dateISO: [true, 'msg'] | 必须为正确格式的日期(ISO),只验证格式,不验证有效性。 |
creditcard: [true, 'msg'] | 必须为正确格式的信用卡号 |
max: [10, 'msg'] | 不能大于10 |
min: [5, 'msg'] | 不能小于5 |
range: [[5,10], 'msg'] | 介于 5 和 10 之间 |
maxlength: [10, 'msg'] | 长度最长为10 |
minlength: [5, 'msg'] | 长度最短为5 |
rangelength: [[5,10], 'msg'] | 长度介于5和10之间 |
equalTo:"#field" | 必须与#field表单等值 |
remote: ["check.php", 'msg' ] | ajax 方法调用 check.php 验证输入值 |
自定义规则
直接看下面用法里的custom,可定义多个自定义规则
用法
validateForm('#myForm',{
rules: {
phone:{
required: [true, '请先输入手机号'],
checkPhone:[true, '手机号码格式有误']
},
verifyCode:{
required: [true, '请先输入验证码'],
minlength: [6, '验证码长度为6位'],
number: [true, '验证码必须为数字']
},
password:{
required: [true, '请输入密码'],
minlength: [6, '密码至少6位']
},
confirm:{
required: [true, '请输入确认密码'],
minlength: [6, '确认密码至少6位'],
equalTo: ['#password', '前后密码不一致']
}
},
custom:[{ //自定义
name: 'checkPhone',
regexp: /^1[3,5,7,8]\d{9}$/
}],
init:function(){}, //初始化
success:function(){} //验证成功
});
封装-若公用库已有则无需引入
function validateForm(target, option){
var $target=$(target);
$target.validate({
//错误显示位置
errorPlacement: function(error, element) {
// Append error within linked label
alert($(error).html());
},
errorElement: "span",
onsubmit:false,
onfocusout:false,
onkeyup:false,
//验证规则
rules: splitRules(option.rules,0),
//提示信息
messages: splitRules(option.rules,1)
});
//自定义验证方法
var custom=option.custom;
if(custom){
for(var i=0;i<custom.length;i++){
var regexp=custom[i]['regexp'];
$.validator.addMethod(custom[i]['name'],function(value,element,params){
return this.optional(element)||(regexp.test(value));
});
}
}
//初始化
option.init&&option.init();
//表单提示
inputInfo(target);
//逐个验证
$target.find('[type="submit"]').click(function(e){
e.preventDefault();
if(validateEach()){
option.success&&option.success(); //验证成功
}
});
//函数-规则提示分解
function splitRules(obj,type) {
var split=function (obj){
var str, newobj={};
//console.log(type);
if(typeof obj !== 'object'){
return;
} else {
for(var i in obj){
newobj[i] = obj[i] instanceof Object ? split(obj[i]) : obj[i];
if(obj[i] instanceof Array){
newobj[i]=newobj[i][type];
}
}
}
return newobj;
}
return split(obj);
}
//函数-表单提示及清除
function inputInfo(form){
var $input=$(form).find('input:not([type="hidden"],[type="file"])'),
$select=$(form).find('select');
$input.focus(function(){
var val=$(this).val();
if(val!=''){
$(this).parents('.baie-cell').removeClass('baie-cell_warn').addClass('baie-cell_clear');
}
});
$input.keyup(function(){
var $parent=$(this).parents('.baie-cell'), val=$(this).val();
$parent.removeClass('baie-cell_warn');
if(val!=''){
$parent.addClass('baie-cell_clear');
}else{
$parent.removeClass('baie-cell_clear');
}
});
$input.blur(function(){
var $this=$(this),$parent=$this.parents('.baie-cell');
setTimeout(function(){
$this.parents('.baie-cell').removeClass('baie-cell_clear');
},50);
});
$('.baie-input_info').click(function(){
$(this).parents('.baie-cell_clear').find('input').val('');
});
$select.change(function(){
var val=$(this).val();
if(val!=''){
$(this).parents('.baie-cell').removeClass('baie-cell_warn');
}
});
}
//函数-逐个验证
function validateEach(){
var isTrue;
for(var propName in option.rules){
var $input=$target.find('[name="'+propName+'"]');
isTrue=$target.validate().element($input);
if(!isTrue){
$target.find('.baie-cell').removeClass('baie-cell_warn');
$input.parents('.baie-cell').addClass('baie-cell_warn');
break;
}
}
return isTrue;
}
}