摘要: 第一步我们要把这些校验逻辑都封装成策略对象://策略对象 var strategies = { isNonEmpty: function (value, errorMsg) { if (value === '') { return errorMsg ...
- //策略对象
- var strategies = {
- isNonEmpty: function(value, errorMsg) {
- if (value === '') {
- return errorMsg
- }
- },
- minLength: 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
- }
- }
- }
- var form = document.getElementById('registerForm');
- var btn = document.getElementById('submit');
- btn.onclick = function() {
- console.log(form.userName.value) var validator = new Validator();
- validator.add(form.userName, [{
- strategy: 'isNonEmpty',
- errorMsg: '用户名不能为空'
- },
- {
- strategy: 'minLength:6',
- errorMsg: '用户名长度不能小于6'
- }]) validator.add(form.password, [{
- strategy: 'minLength:6',
- errorMsg: '密码长度不能小于6'
- }]) validator.add(form.phoneNumber, [{
- strategy: 'isMobile',
- errorMsg: '手机号格式不正确'
- }]) var error = validator.start();
- if (error) {
- alert(error)
- }
- return false
- }
- 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 strategyArr = rule.strategy.split(':');
- var errorMsg = rule.errorMsg
- self.cache.push(function () {
- var strategy = strategyArr.shift()
- strategyArr.unshift(dom.value)
- strategyArr.push(errorMsg)
- return strategies[strategy].apply(self, strategyArr)
- })
- })(rule)
- }
- }
- Validator.prototype.start = function () {
- for (var i = 0, fun; fun = this.cache[i++];) {
- var errorMsg = fun()
- if (errorMsg) return errorMsg
- }
- }
来源: https://yq.aliyun.com/articles/255054