最近在做公司后台的前端页面用的是layui有需求是要写公共文件来实现表单的即时验证我经过多方查找用了jq的validate来实现的话不多说上代码
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
<link rel="stylesheet" href="utls.css">link>
head>
<body>
<form>
<div class="form_control">
<input class="required" value="[email protected]" type="text" name="email" data-tip="请输入您的邮箱" data-valid="isNonEmpty||isEmail" data-error="email不能为空||邮箱格式不正确">
div>
<div class="form_control">
<input class="required" value="123456789" type="password" data-tip="请输入您的密码" data-valid="isNonEmpty||between:6-16" data-error="密码不能为空||密码长度6-16位" name="nickname">
div>
<div class="form_control">
<input class="required" value="王大锤" type="text" name="email" data-tip="请输入您的姓名" data-valid="isNonEmpty||onlyZh||between:2-5" data-error="姓名不能为空||姓名只能为中文||姓名长度为2-5位">
div>
<div class="form_control">
<span class="required" data-valid="isChecked" data-error="性别必选" data-type="radio">
<label><input type="radio" name="sex">男label>
<label><input type="radio" name="sex">女label>
<label><input type="radio" name="sex">未知label>
span>
div>
<div class="form_control">
<span class="required" data-valid="isChecked" data-error="标签至少选择一项" data-type="checkbox">
<label><input type="checkbox" name="label">红label>
<label><input type="checkbox" name="label">绿label>
<label><input type="checkbox" name="label">蓝label>
span>
div>
<div class="form_control">
<select class="required" data-valid="isNonEmpty" data-error="省份必填">
<option value="">请选择省份option>
<option value="001">001option>
<option value="002">002option>
<option value="003">003option>
<option value="004">004option>
<option value="005">005option>
<option value="006">006option>
<option value="007">007option>
<option value="008">008option>
<option value="009">009option>
<option value="010">010option>
select>
div>
<div>
<input type="submit" value="提交">
div>
form>
<script type="text/javascript" src="jquery-1.11.1.js">script>
<script type="text/javascript" src="jquery-validate.js">script>
<script type="text/javascript">
// 获取表单元素
$('form').validate({
onFocus: function() {
this.parent().addClass('active');
return false;
},
onBlur: function() {
var $parent = this.parent();
var _status = parseInt(this.attr('data-status'));
$parent.removeClass('active');
if (!_status) {
$parent.addClass('error');
}
return false;
}
});
$('form').on('submit', function(event) {
event.preventDefault();
$(this).validate('submitValidate'); //return boolean;
});
script>
body>
html>
*jq-validate文件
/*
引入3个JS文件
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery, window, document);
}
}(function($, window, document, undefined) {
/*************************策略对象*****************************/
var RULES = {
isNonEmpty: function(value, errorMsg) {
//不能为空
if (!value.length) {
return errorMsg;
}
},
minLength: function(value, length, errorMsg) {
//大于
if (value.length < length) {
return errorMsg;
}
},
maxLength: function(value, length, errorMsg) {
//小于
if (value.length < length) {
return errorMsg;
}
},
isMobile: function(value, errorMsg) {
//是否为手机号码
if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
return errorMsg;
}
},
isEmail: function(value, errorMsg) {
//是否为邮箱
if (!/(^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$)/.test(value)) {
return errorMsg;
}
},
between: function(value, range, errorMsg) {
//大于小于
var min = parseInt(range.split('-')[0]);
var max = parseInt(range.split('-')[1]);
if (value.length < min || value.length > max) {
return errorMsg;
}
},
onlyEn: function(value, errorMsg) {
//纯英文
if (!/^[A-Za-z]+$/.test(value)) {
}
},
onlyZh: function(value, errorMsg) {
//纯中文
if (!/^[\u4e00-\u9fa5]+$/.test(value)) {
return errorMsg;
}
},
onlyNum: function(value, errorMsg) {
//数字包含小数
if (!/^[0-9]+([.][0-9]+){0,1}$/.test(value)) {
return errorMsg;
}
},
onlyInt: function(value, errorMsg) {
//整数
if (!/^[0-9]*$/.test(value)) {
return errorMsg;
}
},
isChecked: function(value, errorMsg, el) {
var i = 0;
var $collection = $(el).find('input:checked');
if(!$collection.length){
return errorMsg;
}
}
};
/*************************Validator类*****************************/
var setting = {
type: null,
onBlur: null,
onFocus: null,
onChange: null,
successTip: true
};
var Validator = function() {
this.cache = [];
};
Validator.prototype.add = function(dom, rules) {
var self = this;
for (var i = 0, rule; rule = rules[i++];) {
(function(rule) {
var strategyAry = rule.strategy.split(':');
var errorMsg = rule.errorMsg
self.cache.push(function() {
var strategy = strategyAry.shift(); // 前删匹配方式并赋值
strategyAry.unshift(dom.value); // 前插value值
strategyAry.push(errorMsg); // 后插出错提示
strategyAry.push(dom); // 后插dom
if (!RULES[strategy]) {
$.error('没有' + strategy + '规则,请检查命名或自行定义');
}
return {
errorMsg: RULES[strategy].apply(dom, strategyAry),
el: dom
};
});
}(rule));
}
};
Validator.prototype.start = function() {
var result;
for (var i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
var result = validatorFunc();
if (setting.successTip) {
new Validator().showMsg($(result.el), '', 1);
}
if (result.errorMsg) {
return result;
}
};
return true;
};
Validator.prototype.showMsg = function(target, msg, status, callback) {
//status
// 0 : tip
// 1 : success
// 2 : error
var _current = status ? (status > 1 ? 'error' : 'success') : 'tip';
var $context = target.parent();
var $msg = $context.find('.valid_message');
var _other = target.attr('data-type') || '';
$msg.remove();
$context.removeClass('success tip error').addClass(_current+' '+_other).append('+ msg + '' );
};
var plugin = {
init: function(options) {
var $form = this;
var $body = $('body');
var $required = $form.find('.layui-input');
setting = $.extend(setting, options);
if (setting.type) {
$.extend(RULES, setting.type);
}
var validator = new Validator();
$body.on({
focus: function(event) {
var $this = $(this);
var _tipMsg = $this.attr('data-tip') || '';
var _status = $this.attr('data-status');
if (_status === undefined ||!parseInt(_status)) {
validator.showMsg($this, _tipMsg);
}
setting.onFocus ? setting.onFocus.call($this, arguments) : '';
},
blur: function(event) {
var $this = $(this);
var dataValid = $this.attr('data-valid');
if (!dataValid ) {
return;
} else {
var validLen = dataValid.split('||');
}
var errCollection = $this.attr('data-error');
var errMsgAry = errCollection.split("||");
var strategyAry, strategy, errMsg;
for (var i = 0; i < validLen.length; i++) {
strategyAry = validLen[i].split(':');
strategy = strategyAry.shift();
strategyAry.unshift(this.value);
strategyAry.push(errMsgAry[i]);
strategyAry.push(this);
errMsg = RULES[strategy].apply(this, strategyAry);
if (errMsg) {
$this.attr('data-status', 0);
validator.showMsg($this, errMsg, 2);
break;
}
};
if (!errMsg) {
$this.attr('data-status', 1);
//
console.log("成功")
$this.css("border-color", "cadetblue")
setting.successTip ? validator.showMsg($this, '', 1) : $this.parent().find('.valid_message').remove();
}else{
console.log("失败")
$this.css("border-color", "red")
}
setting.onBlur ? setting.onBlur.call($this, arguments) : '';
},
change: function(event) {
setting.onChange ? setting.onChange.call($this, arguments) : '';
}
}, '.layui-input');
},
submitValidate: function(options) {
var $form = options || this;
var $body = $('body');
var $required = $form.find('.layui-input');
var validator = new Validator();
var $target;
$.each($required, function(index, el) {
var $el = $(el);
var dataValid = $el.attr('data-valid');
var validLen = dataValid.split('||');
var errCollection = $el.attr('data-error');
var errMsgAry = errCollection.split("||");
var ruleAry = [];
for (var i = 0; i < validLen.length; i++) {
ruleAry.push({
strategy: validLen[i],
errorMsg: errMsgAry[i]
});
};
validator.add(el, ruleAry);
});
var result = validator.start();
if (result.errorMsg) {
$target = $(result.el);
//$target.attr('data-status', 0)[0].focus();
validator.showMsg($target, result.errorMsg, 2);
return false;
}
return true;
}
};
$.fn.validate = function() {
var method = arguments[0];
if (plugin[method]) {
method = plugin[method];
arguments = Array.prototype.slice.call(arguments, 1);
} else if (typeof(method) == 'object' || !method) {
method = plugin.init;
} else {
$.error('Method ' + method + ' does not exist on jQuery.validate Plugin');
return this;
}
return method.apply(this, arguments);
}
}))
用法已经写在上面了,有更好的方法可以留言联系我