思路
选择在input的中直接截取字段进行验证,使用一个自定的属性对用户输入的字符串进行判断
<div class="form">
<form action="">
<div class="input-wrap">
<label for="">姓名</label>
<input data-rule="maxlength:10|minlength:2|nullable:false|numeric:false" type="text" class="input-control">
<div class="input-error">姓名格式输入有误</div>
</div>
</form>
</div>
所以要是一个验证模块
实现Vaildator模块
/**
* Vaildator验证
*/
$(function () {
'use strict';
window.Validator = function (val, rule) {
this.is_valid = function (new_val) {
var key;
if (new_val !== undefined)
val = new_val;
/*若不是必填项,且用户未填写任何内容则直接判定为合法*/
if (!rule.required && !val)
return true;
for (key in rule) {
/*防止重复检查*/
if (key === 'required')
continue;
/*防止调用rule中相对应的方法*/
var r = this['validate_' + key]();
if (!r)
return false;
}
return true;
}
this.validate_max = function () {
preMaxMin();
return val <= rule.max;
}
this.validate_min = function () {
preMaxMin();
return val >= rule.min;
}
this.validate_maxlength = function () {
preLength();
return val.length <= rule.maxlength;
}
this.validate_minlength = function () {
preLength();
return val.length >= rule.minlength;
}
this.validate_numeric = function () {
return $.isNumeric(val);
}
this.validate_required = function () {
//防止空格
var real = $.trim(val);
if (!real && real !== 0)
return false;
return true;
}
this.validate_pattern = function () {
var reg = new RegExp(rule.pattern);
return reg.test(val);
}
/*用于完成min,max方法的前置工作*/
function preMaxMin() {
val = parseFloat(val);
}
/*用于完成minleng,maxleng方法的前置工作*/
function preLength() {
val = val.toString();
}
}
});
实现Input
/**
* Created by tazbingo on 2017/9/26.
*/
$(function () {
'use strict';
window.Input = function (selector) {
var $ele
, $error_ele
, me = this
, rule =
{
required: true
};
this.loadValidator = function () {
var val = this.getVal();
this.validator = new Validator(val, rule);
}
this.getVal = function () {
return $ele.val();
}
function init() {
findEle();
get_error_ele();
parseRule();
me.loadValidator();
listen();
}
function listen() {
$ele.on('blur', function () {
var valid = me.validator.is_valid(me.getVal());
console.log('blur' + valid);
if (valid)
$error_ele.hide();
else
$error_ele.show();
});
}
function get_error_ele() {
$error_ele = $(get_error_selector());
}
function get_error_selector() {
return '#' + $ele.attr('name') + '-input-error';
}
function findEle() {
if (selector instanceof jQuery)
$ele = selector;
else
$ele = $(selector);
}
function parseRule() {
var i;
var ruleString = $ele.data('rule');
if (!ruleString) return;
var rule_arr = ruleString.split('|');//['min:18','maxlength:10']
for (i = 0; i < rule_arr.length; i++) {
var item_str = rule_arr[i];
var item_arr = item_str.split(':'); //['min','18']
rule[item_arr[0]] = JSON.parse(item_arr[1]); //['min:18']
}
}
init();
}
});
网友评论