-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy_form_validate.html
112 lines (100 loc) · 2.52 KB
/
strategy_form_validate.html
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
108
109
110
111
112
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Strategy</title>
</head>
<body>
<form class="validateForm">
<label for="fieldName">Name: <input type="text" id="fieldName" class="validate" value="Apple" data-validate="isNonEmpty">
<label for="fieldMobile">Mobile: <input type="text" id="fieldMobile" class="validate" value="0912-345678">
<a href="#" class="submit">validate!</a>
</form>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
(function($) {
$.fn.formValidator = function(opts) {
// default configuration
var config = $.extend({}, {
opt1: null
}, opts);
// main function
function init(obj) {
var dObj = $(obj),
dValidateItems = dObj.find('.validate'),
dSubmitBtn = dObj.find('.submit');
var validator = {
types: {},
messages: [],
config: {},
validate: function(data){
var i,
msg,
type,
checker,
result_ok;
this.messages = [];
for(i in data){
if(data.hasOwnProperty(i)){ //i == name
type = this.config[i]; //type == config[name] == isNonEmpty
checker = this.types[type]; //checker == types[isNonEmpty] == {}
//要檢測的條件不存在,無法檢測
if(!type){
continue;
}
//要檢測的規則和錯誤訊息不存在,無法檢測,拋出異常
if(!checker){
continue
}
//驗證
result_ok = checker.validate(data[i]);
if(!result_ok){
msg = "Invalid value for *" + i + "*, " + checker.errMsg;
this.messages.push(msg);
}
else{
console.log('Everything is OK!');
}
}
}
},
hasErrors: function(){
var result = this.messages.length !== 0;
return result;
}
};
validator.types.isNonEmpty = {
validate: function(value){
return value !== "";
},
errMsg: 'the value cannot be empty'
};
dSubmitBtn.click(function(e){
e.preventDefault();
var data = {};
$.each(dValidateItems, function(i, val){
data[$(val).attr('id')] = $(val).val();
});
$.each(dValidateItems, function(i, val){
validator.config[$(val).attr('id')] = $(val).data('validate');
});
validator.validate(data);
if(validator.hasErrors()){
console.log(validator.messages.join('\n'));
}
});
}
// initialize every element
this.each(function() {
init($(this));
});
return this;
};
// start
$(function() {
$('.validateForm').formValidator();
});
})(jQuery);
</script>
</body>
</html>