forked from andyet/Happy.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhappy.js
97 lines (88 loc) · 2.8 KB
/
happy.js
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
(function($){
function trim(el) {
return (''.trim) ? el.val().trim() : $.trim(el.val());
}
$.fn.isHappy = function (config) {
var fields = [], item;
function getError(error) {
return $('<span id="'+error.id+'" class="unhappyMessage">'+error.message+'</span>');
}
function handleSubmit() {
var errors = false, i, l;
for (i = 0, l = fields.length; i < l; i += 1) {
if (!fields[i].testValid(true)) {
errors = true;
}
}
if (errors) {
if (isFunction(config.unHappy)) config.unHappy();
return false;
} else if (config.testMode) {
if (window.console) console.warn('would have submitted');
return false;
}
}
function isFunction (obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
}
function processField(opts, selector) {
var field = $(selector),
error = {
message: opts.message,
id: selector.slice(1) + '_unhappy'
},
errorEl = $(error.id).length > 0 ? $(error.id) : getError(error);
fields.push(field);
field.testValid = function (submit) {
var val,
el = $(this),
gotFunc,
error = false,
temp,
required = !!el.get(0).attributes.getNamedItem('required') || opts.required,
password = (field.attr('type') === 'password'),
arg = isFunction(opts.arg) ? opts.arg() : opts.arg;
// clean it or trim it
if (isFunction(opts.clean)) {
val = opts.clean(el.val());
} else if (!opts.trim && !password) {
val = trim(el);
} else {
val = el.val();
}
// write it back to the field
el.val(val);
// get the value
gotFunc = ((val.length > 0 || required === 'sometimes') && isFunction(opts.test));
// check if we've got an error on our hands
if (submit === true && required === true && val.length === 0) {
error = true;
} else if (gotFunc) {
error = !opts.test(val, arg);
}
if (error) {
el.addClass('unhappy').before(errorEl);
return false;
} else {
temp = errorEl.get(0);
// this is for zepto
if (temp.parentNode) {
temp.parentNode.removeChild(temp);
}
el.removeClass('unhappy');
return true;
}
};
field.bind(config.when || 'blur', field.testValid);
}
for (item in config.fields) {
processField(config.fields[item], item);
}
if (config.submitButton) {
$(config.submitButton).click(handleSubmit);
} else {
this.bind('submit', handleSubmit);
}
return this;
};
})(this.jQuery || this.Zepto);