html+input添加校验,给某个文本框添加多种校验规则(示例代码)

请输入用户名:请输入密码:请输入手机号码:

/***************策略对象*************/

var strategies ={

isNotEmpty:function(value,errorMsg){if(value === ‘‘){returnerrorMsg;

}

},

minLength:function(value,length,errorMsg){if(value.length

}

},

isMobile:function(){if(!/(^1[3|5|8][0-9]{9}$)/.test(value)){returnerrorMsg;

}

}

}/***************validator类***************/

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.solit(‘:‘);var errorMsg =rule.errorMsg;

self.cache.push(function(){var strategy =strategyAry.shift();

strategyAry.unshift(dom.value);

strategyAry.push(errorMsg);returnstrategies[strategy].apply(dom,strategyAry);

})

})(rule);

}

}

Validator.prototype.start=function(){for(var i=0,validatorFunc;validatorFunc = this.cache[i++];){var errorMsg =validatorFunc();if(errorMsg){returnerrorMsg;

}

}

}/************客户调用代码***********/

var registerForm = document.getElementById(‘registerForm‘);var validatorFunc =function(){var validator = newValidator();

validator.add(registerForm.userName,[{

strategy:‘isNotEmpty‘,

errorMsg:‘用户名不能为空‘},{strategy:‘minLength:10‘,

errorMsg:‘用户名长度不能小于10位‘}]);

validator.add(registerForm.passWord,[{

strategy:‘minLength:6‘,

errorMsg:‘用户密码不能小于6位‘}]);

validator.add(registerForm.phoneNumber,[{

strategy:‘isMobile‘,

errorMsg:‘手机号码格式不正确‘}]);var errorMsg =validator.start();returnerrorMsg;

}

registerForm.οnsubmit=function(){var errorMsg =validatorFunc();if(errorMsg){

alert(errorMsg);return false;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值