forked from ryanseddon/H5F
-
Notifications
You must be signed in to change notification settings - Fork 0
/
h5f.js
328 lines (294 loc) · 11.8 KB
/
h5f.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*! H5F - v1.0.0 - 2012-06-01
* https://github.com/ryanseddon/H5F/
* Copyright (c) 2012 Ryan Seddon; Licensed MIT */
var H5F = H5F || {};
(function(d){
var field = d.createElement("input"),
emailPatt = /^[a-zA-Z0-9.!#$%&'*+-\/=?\^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
urlPatt = /[a-z][\-\.+a-z]*:\/\//i,
nodes = /^(input|select|textarea)$/i,
isSubmit, usrPatt, curEvt, args, custMsg = "",
// Methods
setup, validation, validity, checkField, checkValidity, setCustomValidity, support, pattern, placeholder, range, required, valueMissing, listen, unlisten, preventActions, getTarget, addClass, removeClass, isHostMethod;
setup = function(form,settings) {
var isCollection = !form.nodeType || false;
var opts = {
validClass : "valid",
invalidClass : "error",
requiredClass : "required",
placeholderClass : "placeholder"
};
if(typeof settings === "object") {
for (var i in opts) {
if(typeof settings[i] === "undefined") { settings[i] = opts[i]; }
}
}
args = settings || opts;
if(isCollection) {
for(var k=0,len=form.length;k<len;k++) {
validation(form[k]);
}
} else {
validation(form);
}
};
validation = function(form) {
var f = form.elements,
flen = f.length,
isRequired, noValidate = !!(form.attributes["novalidate"]);
listen(form,"invalid",checkField,true);
listen(form,"blur",checkField,true);
listen(form,"input",checkField,true);
listen(form,"keyup",checkField,true);
listen(form,"focus",checkField,true);
listen(form,"submit",function(e){
isSubmit = true;
if(!noValidate && !form.checkValidity()) {
preventActions(e);
}
},false);
if(!support()) {
form.checkValidity = function() { return checkValidity(form); };
while(flen--) {
isRequired = !!(f[flen].attributes["required"]);
// Firefox includes fieldsets inside elements nodelist so we filter it out.
if(f[flen].nodeName !== "FIELDSET") {
validity(f[flen]); // Add validity object to field
}
}
}
};
validity = function(el) {
var elem = el,
missing = valueMissing(elem),
attrs = {
type: elem.getAttribute("type"),
pattern: elem.getAttribute("pattern"),
placeholder: elem.getAttribute("placeholder")
},
isType = /^(email|url)$/i,
evt = /^(input|keyup)$/i,
fType = ((isType.test(attrs.type)) ? attrs.type : ((attrs.pattern) ? attrs.pattern : false)),
patt = pattern(elem,fType),
step = range(elem,"step"),
min = range(elem,"min"),
max = range(elem,"max"),
customError = (custMsg !== "");
elem.checkValidity = function() { return checkValidity.call(this,elem); };
elem.setCustomValidity = function(msg) { setCustomValidity.call(elem,msg); };
elem.validationMessage = custMsg;
elem.validity = {
valueMissing: missing,
patternMismatch: patt,
rangeUnderflow: min,
rangeOverflow: max,
stepMismatch: step,
customError: customError,
valid: (!missing && !patt && !step && !min && !max && !customError)
};
if(attrs.placeholder && !evt.test(curEvt)) { placeholder(elem); }
};
checkField = function (e) {
var el = getTarget(e) || e, // checkValidity method passes element not event
events = /^(input|keyup|focusin|focus)$/i,
ignoredTypes = /^(submit|image|button|reset)$/i,
checkForm = true;
if(nodes.test(el.nodeName) && !(ignoredTypes.test(el.type) || ignoredTypes.test(el.nodeName))) {
curEvt = e.type;
if(!support()) { validity(el); }
if(el.validity.valid && el.value !== "" || el.value !== el.getAttribute("placeholder") && el.validity.valid) {
removeClass(el,[args.invalidClass,args.requiredClass]);
addClass(el,args.validClass);
} else if(!events.test(curEvt)) {
if(el.validity.valueMissing) {
removeClass(el,[args.invalidClass,args.validClass]);
addClass(el,args.requiredClass);
} else if(!el.validity.valid) {
removeClass(el,[args.validClass,args.requiredClass]);
addClass(el,args.invalidClass);
}
} else if(el.validity.valueMissing) {
removeClass(el,[args.requiredClass,args.invalidClass,args.validClass]);
}
if(curEvt === "input" && checkForm) {
// If input is triggered remove the keyup event
unlisten(el.form,"keyup",checkField,true);
checkForm = false;
}
}
};
checkValidity = function (el) {
var f, ff, isRequired, hasPattern, invalid = false;
if(el.nodeName === "FORM") {
f = el.elements;
for(var i = 0,len = f.length;i < len;i++) {
ff = f[i];
isRequired = !!(ff.attributes["required"]);
hasPattern = !!(ff.attributes["pattern"]);
if(ff.nodeName !== "FIELDSET" && (isRequired || hasPattern && isRequired)) {
checkField(ff);
if(!ff.validity.valid && !invalid) {
if(isSubmit) { // If it's not a submit event the field shouldn't be focused
ff.focus();
}
invalid = true;
}
}
}
return !invalid;
} else {
checkField(el);
return el.validity.valid;
}
};
setCustomValidity = function (msg) {
var el = this;
custMsg = msg;
el.validationMessage = custMsg;
};
support = function() {
return (isHostMethod(field,"validity") && isHostMethod(field,"checkValidity"));
};
// Create helper methods to emulate attributes in older browsers
pattern = function(el, type) {
if(type === "email") {
return !emailPatt.test(el.value);
} else if(type === "url") {
return !urlPatt.test(el.value);
} else if(!type) {
return false;
} else {
var placeholder = el.getAttribute("placeholder"),
val = el.value;
usrPatt = new RegExp('^(?:' + type + ')$');
if(val === placeholder) {
return true;
} else if(val === "") {
return false;
} else {
return !usrPatt.test(el.value);
}
}
};
placeholder = function(el) {
var attrs = { placeholder: el.getAttribute("placeholder") },
focus = /^(focus|focusin|submit)$/i,
node = /^(input|textarea)$/i,
ignoredType = /^password$/i,
isNative = !!("placeholder" in field);
if(!isNative && node.test(el.nodeName) && !ignoredType.test(el.type)) {
if(el.value === "" && !focus.test(curEvt)) {
el.value = attrs.placeholder;
listen(el.form,'submit', function () {
curEvt = 'submit';
placeholder(el);
}, true);
addClass(el,args.placeholderClass);
} else if(el.value === attrs.placeholder && focus.test(curEvt)) {
el.value = "";
removeClass(el,args.placeholderClass);
}
}
};
range = function(el,type) {
// Emulate min, max and step
var min = parseInt(el.getAttribute("min"),10) || 0,
max = parseInt(el.getAttribute("max"),10) || false,
step = parseInt(el.getAttribute("step"),10) || 1,
val = parseInt(el.value,10),
mismatch = (val-min)%step;
if(!valueMissing(el) && !isNaN(val)) {
if(type === "step") {
return (el.getAttribute("step")) ? (mismatch !== 0) : false;
} else if(type === "min") {
return (el.getAttribute("min")) ? (val < min) : false;
} else if(type === "max") {
return (el.getAttribute("max")) ? (val > max) : false;
}
} else if(el.getAttribute("type") === "number") {
return true;
} else {
return false;
}
};
required = function(el) {
var required = !!(el.attributes["required"]);
return (required) ? valueMissing(el) : false;
};
valueMissing = function(el) {
var placeholder = el.getAttribute("placeholder"),
isRequired = !!(el.attributes["required"]);
return !!(isRequired && (el.value === "" || el.value === placeholder));
};
/* Util methods */
listen = function (node,type,fn,capture) {
if(isHostMethod(window,"addEventListener")) {
/* FF & Other Browsers */
node.addEventListener( type, fn, capture );
} else if(isHostMethod(window,"attachEvent") && typeof window.event !== "undefined") {
/* Internet Explorer way */
if(type === "blur") {
type = "focusout";
} else if(type === "focus") {
type = "focusin";
}
node.attachEvent( "on" + type, fn );
}
};
unlisten = function (node,type,fn,capture) {
if(isHostMethod(window,"removeEventListener")) {
/* FF & Other Browsers */
node.removeEventListener( type, fn, capture );
} else if(isHostMethod(window,"detachEvent") && typeof window.event !== "undefined") {
/* Internet Explorer way */
node.detachEvent( "on" + type, fn );
}
};
preventActions = function (evt) {
evt = evt || window.event;
if(evt.stopPropagation && evt.preventDefault) {
evt.stopPropagation();
evt.preventDefault();
} else {
evt.cancelBubble = true;
evt.returnValue = false;
}
};
getTarget = function (evt) {
evt = evt || window.event;
return evt.target || evt.srcElement;
};
addClass = function (e,c) {
var re;
if (!e.className) {
e.className = c;
}
else {
re = new RegExp('(^|\\s)' + c + '(\\s|$)');
if (!re.test(e.className)) { e.className += ' ' + c; }
}
};
removeClass = function (e,c) {
var re, m, arr = (typeof c === "object") ? c.length : 1, len = arr;
if (e.className) {
if (e.className === c) {
e.className = '';
}
else {
while(arr--) {
re = new RegExp('(^|\\s)' + ((len > 1) ? c[arr] : c) + '(\\s|$)');
m = e.className.match(re);
if (m && m.length === 3) { e.className = e.className.replace(re, (m[1] && m[2])?' ':''); }
}
}
}
};
isHostMethod = function(o, m) {
var t = typeof o[m], reFeaturedMethod = new RegExp('^function|object$', 'i');
return !!((reFeaturedMethod.test(t) && o[m]) || t === 'unknown');
};
// Since all methods are only used internally no need to expose globally
window["H5F"] = {
setup: setup
};
}(document));