<table class="html5">
<tr class="li1"><td class="ln"><pre class="de1">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107 > > >策略模式-校验表单> > > > > 用户名: > 密码: > 手机号码: > >提交> > > // 策略对象 var strategies = { isNoEmpty: function (value,errorMsg) { if (value === '') { return errorMsg; } }, isNoSpace: function (value,errorMsg) { if (value.trim() === '') { return errorMsg; } }, minLength: function (value,length,errorMsg) { if (value.trim().length , : function ,errorMsg .length > length) { return errorMsg; } }, isMobile: function (value,errorMsg) { if (!/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|17[7]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(value)) { return errorMsg; } } } // 验证类 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); strategyAry.push(errorMsg); return strategies[strategy].apply(dom,strategyAry); }) })(rule) } }; Validator.prototype.start = function() { for(var i = 0,validatorFunc; validatorFunc = this.cache[i++];) { var errorMsg = validatorFunc(); if (errorMsg) { return errorMsg; } } }; // 调用代码 var registerForm = document.getElementById('registerForm'); var validataFunc = function() { var validator = new Validator(); validator.add(registerForm.userName,[{ strategy: 'isNoEmpty', errorMsg: '用户名不可为空' },{ strategy: 'isNoSpace', errorMsg: '不允许以空白字符命名' },{ strategy: 'minLength:2', errorMsg: '用户名长度不能小于2位' }]); validator.add(registerForm.password,[ { strategy: 'minLength:6', errorMsg: '密码长度不能小于6位' }]); validator.add(registerForm.phoneNumber,[{ strategy: 'isMobile', errorMsg: '请输入正确的手机号码格式' }]); var errorMsg = validator.start(); return errorMsg; } registerForm.onsubmit = function() { var errorMsg = validataFunc(); if (errorMsg) { alert(errorMsg); return false; } } > > > 原文链接:https://www.f2er.com/note/421564.html