-
Notifications
You must be signed in to change notification settings - Fork 462
Expand file tree
/
Copy pathcore-validators.js
More file actions
354 lines (315 loc) · 12.5 KB
/
Copy pathcore-validators.js
File metadata and controls
354 lines (315 loc) · 12.5 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/**
* File declaring all default validators.
*/
(function($) {
/*
* Validate email
*/
$.formUtils.addValidator({
name: 'email',
validatorFunction: function (email) {
var emailParts = email.toLowerCase().split('@'),
localPart = emailParts[0],
domain = emailParts[1];
if (localPart && domain) {
if( localPart.indexOf('"') === 0 ) {
var len = localPart.length;
localPart = localPart.replace(/\"/g, '');
if( localPart.length !== (len-2) ) {
return false; // It was not allowed to have more than two apostrophes
}
}
return $.formUtils.validators.validate_domain.validatorFunction(emailParts[1]) &&
localPart.indexOf('.') !== 0 &&
localPart.substring(localPart.length-1, localPart.length) !== '.' &&
localPart.indexOf('..') === -1 &&
!(/[^\w\+\.\-\#\-\_\~\!\$\&\'\(\)\*\+\,\;\=\:]/.test(localPart));
}
return false;
},
errorMessage: '',
errorMessageKey: 'badEmail'
});
/*
* Validate domain name
*/
$.formUtils.addValidator({
name: 'domain',
validatorFunction: function (val) {
return val.length > 0 &&
val.length <= 253 && // Including sub domains
!(/[^a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]/.test(val.slice(-2))) && !(/[^a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]/.test(val.substr(0, 1))) && !(/[^a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\.\-]/.test(val)) &&
val.split('..').length === 1 &&
val.split('.').length > 1;
},
errorMessage: '',
errorMessageKey: 'badDomain'
});
/*
* Validate required
*/
$.formUtils.addValidator({
name: 'required',
validatorFunction: function (val, $el, config, language, $form) {
switch ($el.attr('type')) {
case 'checkbox':
return $el.is(':checked');
case 'radio':
return $form.find('input[name="' + $el.attr('name') + '"]').filter(':checked').length > 0;
default:
return $.trim(val) !== '';
}
},
errorMessage: '',
errorMessageKey: function(config) {
if (config.errorMessagePosition === 'top' || typeof config.errorMessagePosition === 'function') {
return 'requiredFields';
}
else {
return 'requiredField';
}
}
});
/*
* Validate length range
*/
$.formUtils.addValidator({
name: 'length',
validatorFunction: function (val, $el, conf, lang) {
var lengthAllowed = $el.valAttr('length'),
type = $el.attr('type');
if (lengthAllowed === undefined) {
alert('Please add attribute "data-validation-length" to ' + $el[0].nodeName + ' named ' + $el.attr('name'));
return true;
}
// check if length is above min, below max or within range.
var len = type === 'file' && $el.get(0).files !== undefined ? $el.get(0).files.length : val.length,
lengthCheckResults = $.formUtils.numericRangeCheck(len, lengthAllowed),
checkResult;
switch (lengthCheckResults[0]) { // outside of allowed range
case 'out':
this.errorMessage = lang.lengthBadStart + lengthAllowed + lang.lengthBadEnd;
checkResult = false;
break;
// too short
case 'min':
this.errorMessage = lang.lengthTooShortStart + lengthCheckResults[1] + lang.lengthBadEnd;
checkResult = false;
break;
// too long
case 'max':
this.errorMessage = lang.lengthTooLongStart + lengthCheckResults[1] + lang.lengthBadEnd;
checkResult = false;
break;
// ok
default:
checkResult = true;
}
return checkResult;
},
errorMessage: '',
errorMessageKey: ''
});
/*
* Validate url
*/
$.formUtils.addValidator({
name: 'url',
validatorFunction: function (url) {
// written by Scott Gonzalez: http://projects.scottsplayground.com/iri/
// - Victor Jonsson added support for arrays in the url ?arg[]=sdfsdf
// - General improvements made by Stéphane Moureau <https://github.com/TraderStf>
var urlFilter = /^(https?|ftp):\/\/((((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])(\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])(\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/(((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|\[|\]|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#(((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
if (urlFilter.test(url)) {
var domain = url.split('://')[1],
domainSlashPos = domain.indexOf('/');
if (domainSlashPos > -1) {
domain = domain.substr(0, domainSlashPos);
}
return $.formUtils.validators.validate_domain.validatorFunction(domain); // todo: add support for IP-addresses
}
return false;
},
errorMessage: '',
errorMessageKey: 'badUrl'
});
/*
* Validate number (floating or integer)
*/
$.formUtils.addValidator({
name: 'number',
validatorFunction: function (val, $el, conf) {
if (val !== '') {
var allowing = $el.valAttr('allowing') || '',
decimalSeparator = $el.valAttr('decimal-separator') || conf.decimalSeparator,
allowsRange = false,
begin, end,
steps = $el.valAttr('step') || '',
allowsSteps = false,
sanitize = $el.attr('data-sanitize') || '',
isFormattedWithNumeral = sanitize.match(/(^|[\s])numberFormat([\s]|$)/i);
if (isFormattedWithNumeral) {
if (!window.numeral) {
throw new ReferenceError('The data-sanitize value numberFormat cannot be used without the numeral' +
' library. Please see Data Validation in http://www.formvalidator.net for more information.');
}
//Unformat input first, then convert back to String
if (val.length) {
val = String(numeral().unformat(val));
}
}
if (allowing.indexOf('number') === -1) {
allowing += ',number';
}
if (allowing.indexOf('negative') === -1 && val.indexOf('-') === 0) {
return false;
}
if (allowing.indexOf('range') > -1) {
begin = parseFloat(allowing.substring(allowing.indexOf('[') + 1, allowing.indexOf(';')));
end = parseFloat(allowing.substring(allowing.indexOf(';') + 1, allowing.indexOf(']')));
allowsRange = true;
}
if (steps !== '') {
allowsSteps = true;
}
if (decimalSeparator === ',') {
if (val.indexOf('.') > -1) {
return false;
}
// Fix for checking range with floats using ,
val = val.replace(',', '.');
}
if (val.replace(/[0-9-]/g, '') === '' && (!allowsRange || (val >= begin && val <= end)) && (!allowsSteps || (val % steps === 0))) {
return true;
}
if (allowing.indexOf('float') > -1 && val.match(new RegExp('^([0-9-]+)\\.([0-9]+)$')) !== null && (!allowsRange || (val >= begin && val <= end)) && (!allowsSteps || (val % steps === 0))) {
return true;
}
}
return false;
},
errorMessage: '',
errorMessageKey: 'badInt'
});
/*
* Validate alpha numeric
*/
$.formUtils.addValidator({
name: 'alphanumeric',
validatorFunction: function (val, $el, conf, language) {
var patternStart = '^([a-zA-Z0-9',
patternEnd = ']+)$',
additionalChars = $el.valAttr('allowing'),
pattern = '',
hasSpaces = false;
if (additionalChars) {
pattern = patternStart + additionalChars + patternEnd;
var extra = additionalChars.replace(/\\/g, '');
if (extra.indexOf(' ') > -1) {
hasSpaces = true;
extra = extra.replace(' ', '');
extra += language.andSpaces || $.formUtils.LANG.andSpaces;
}
if(language.badAlphaNumericAndExtraAndSpaces && language.badAlphaNumericAndExtra) {
if(hasSpaces) {
this.errorMessage = language.badAlphaNumericAndExtraAndSpaces + extra;
} else {
this.errorMessage = language.badAlphaNumericAndExtra + extra + language.badAlphaNumericExtra;
}
} else {
this.errorMessage = language.badAlphaNumeric + language.badAlphaNumericExtra + extra;
}
} else {
pattern = patternStart + patternEnd;
this.errorMessage = language.badAlphaNumeric;
}
return new RegExp(pattern).test(val);
},
errorMessage: '',
errorMessageKey: ''
});
/*
* Validate against regexp
*/
$.formUtils.addValidator({
name: 'custom',
validatorFunction: function (val, $el) {
var regexp = new RegExp($el.valAttr('regexp'));
return regexp.test(val);
},
errorMessage: '',
errorMessageKey: 'badCustomVal'
});
/*
* Validate date
*/
$.formUtils.addValidator({
name: 'date',
validatorFunction: function (date, $el, conf) {
var dateFormat = $el.valAttr('format') || conf.dateFormat || 'yyyy-mm-dd',
addMissingLeadingZeros = $el.valAttr('require-leading-zero') === 'false';
return $.formUtils.parseDate(date, dateFormat, addMissingLeadingZeros) !== false;
},
errorMessage: '',
errorMessageKey: 'badDate'
});
/*
* Validate group of checkboxes, validate qty required is checked
* written by Steve Wasiura : http://stevewasiura.waztech.com
* element attrs
* data-validation="checkbox_group"
* data-validation-qty="1-2" // min 1 max 2
* data-validation-error-msg="chose min 1, max of 2 checkboxes"
*/
$.formUtils.addValidator({
name: 'checkbox_group',
validatorFunction: function (val, $el, conf, lang, $form) {
// preset return var
var isValid = true,
// get name of element. since it is a checkbox group, all checkboxes will have same name
elname = $el.attr('name'),
// get checkboxes and count the checked ones
$checkBoxes = $('input[type=checkbox][name^="' + elname + '"]', $form),
checkedCount = $checkBoxes.filter(':checked').length,
// get el attr that specs qty required / allowed
qtyAllowed = $el.valAttr('qty');
if (qtyAllowed === undefined) {
var elementType = $el.get(0).nodeName;
alert('Attribute "data-validation-qty" is missing from ' + elementType + ' named ' + $el.attr('name'));
}
// call Utility function to check if count is above min, below max, within range etc.
var qtyCheckResults = $.formUtils.numericRangeCheck(checkedCount, qtyAllowed);
// results will be array, [0]=result str, [1]=qty int
switch (qtyCheckResults[0]) {
// outside allowed range
case 'out':
this.errorMessage = lang.groupCheckedRangeStart + qtyAllowed + lang.groupCheckedEnd;
isValid = false;
break;
// below min qty
case 'min':
this.errorMessage = lang.groupCheckedTooFewStart + qtyCheckResults[1] + (lang.groupCheckedTooFewEnd || lang.groupCheckedEnd);
isValid = false;
break;
// above max qty
case 'max':
this.errorMessage = lang.groupCheckedTooManyStart + qtyCheckResults[1] + (lang.groupCheckedTooManyEnd || lang.groupCheckedEnd);
isValid = false;
break;
// ok
default:
isValid = true;
}
if( !isValid ) {
var _triggerOnBlur = function() {
$checkBoxes.unbind('click', _triggerOnBlur);
$checkBoxes.filter('*[data-validation]').validateInputOnBlur(lang, conf, false, 'blur');
};
$checkBoxes.bind('click', _triggerOnBlur);
}
return isValid;
}
// errorMessage : '', // set above in switch statement
// errorMessageKey: '' // not used
});
})(jQuery);