1 | <!DOCTYPE html>
|
2 | <html lang="en">
|
3 | <head>
|
4 | <meta charset="UTF-8" />
|
5 | <meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
6 | <meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
7 | <title>策略模式</title>
|
8 | </head>
|
9 | <body>
|
10 | <form action="#" method="post" id="form">
|
11 | 请输入用户名:<input type="text" name="username" /><br />
|
12 | 请输入密码:<input type="password" name="password" /><br />
|
13 | 请输入手机号:<input type="text" name="phone" /><br />
|
14 | <button>提交</button>
|
15 | </form>
|
16 | <script>
|
17 | var form = document.getElementById("form");
|
18 |
|
19 |
|
20 | var strategies = {
|
21 | isNotEmpty: function (value, errorMsg) {
|
22 | if (value == "") {
|
23 | return errorMsg;
|
24 | }
|
25 | },
|
26 | min: function (value, length, errorMsg) {
|
27 | if (value.length < length) {
|
28 | return errorMsg;
|
29 | }
|
30 | },
|
31 | isMobile: function (value, errorMsg) {
|
32 | if (!/^1[3|5|8][0-9]{9}$/.test(value)) {
|
33 | return errorMsg;
|
34 | }
|
35 | },
|
36 | };
|
37 |
|
38 |
|
39 | class Validator {
|
40 | constructor() {
|
41 | this.cache = [];
|
42 | }
|
43 |
|
44 | add(dom, rule, errorMsg) {
|
45 | var array = rule.split(":");
|
46 | this.cache.push(function () {
|
47 | var strategy = array.shift();
|
48 | array.unshift(dom.value);
|
49 | array.push(errorMsg);
|
50 | return strategies[strategy](...array);
|
51 | });
|
52 | }
|
53 |
|
54 | valid() {
|
55 | for (var i = 0, validatorFunc; (validatorFunc = this.cache[i++]); ) {
|
56 | var msg = validatorFunc();
|
57 | if (msg) {
|
58 |
|
59 | return msg;
|
60 | }
|
61 | }
|
62 | }
|
63 | }
|
64 |
|
65 |
|
66 | var validateFunc = function () {
|
67 | var validator = new Validator();
|
68 |
|
69 | validator.add(form.username, "isNotEmpty", "用户名不能为空");
|
70 | validator.add(form.password, "min:6", "密码的长度不能小于6位");
|
71 | validator.add(form.phone, "isMobile", "手机号格式不正确");
|
72 |
|
73 | var errorMsg = validator.valid();
|
74 | return errorMsg;
|
75 | };
|
76 |
|
77 | form.onsubmit = function () {
|
78 | var errorMsg = validateFunc();
|
79 | if (errorMsg) {
|
80 | alert(errorMsg);
|
81 | return false;
|
82 | }
|
83 | };
|
84 | </script>
|
85 | </body>
|
86 | </html>
|