-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathjquery.validation.js
More file actions
2080 lines (1630 loc) · 64.7 KB
/
jquery.validation.js
File metadata and controls
2080 lines (1630 loc) · 64.7 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* jQuery Form Validation
* Copyright (C) 2015 RunningCoder.org
* Licensed under the MIT license
*
* @author Tom Bertrand
* @version 1.5.3 (2015-12-02)
* @link http://www.runningcoder.org/jqueryvalidation/
*/
;
(function (window, document, $, undefined) {
window.Validation = {
form: [],
labels: {},
hasScrolled: false
};
/**
* Fail-safe preventExtensions function for older browsers
*/
if (typeof Object.preventExtensions !== "function") {
Object.preventExtensions = function (obj) {
return obj;
};
}
// Not using strict to avoid throwing a window error on bad config extend.
// console.debug is used instead to debug Validation
//"use strict";
// =================================================================================================================
/**
* @private
* RegExp rules
*/
var _rules = {
NOTEMPTY: /\S/,
INTEGER: /^\d+$/,
NUMERIC: /^\d+(?:[,\s]\d{3})*(?:\.\d+)?$/,
MIXED: /^[\w\s-]+$/,
NAME: /^['a-zãàáäâẽèéëêìíïîõòóöôùúüûñç\s-]+$/i,
NOSPACE: /^(?!\s)\S*$/,
TRIM: /^[^\s].*[^\s]$/,
DATE: /^\d{4}-\d{2}-\d{2}(\s\d{2}:\d{2}(:\d{2})?)?$/,
EMAIL: /^([^@]+?)@(([a-z0-9]-*)*[a-z0-9]+\.)+([a-z0-9]+)$/i,
URL: /^(https?:\/\/)?((([a-z0-9]-*)*[a-z0-9]+\.?)*([a-z0-9]+))(\/[\w?=\.-]*)*$/,
PHONE: /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/,
OPTIONAL: /\S/,
COMPARISON: /^\s*([LV])\s*([<>]=?|==|!=)\s*([^<>=!]+?)\s*$/
};
/**
* @private
* Error messages
*/
var _messages = {
'default': '$ contain error(s).',
'NOTEMPTY': '$ must not be empty.',
'INTEGER': '$ must be an integer.',
'NUMERIC': '$ must be numeric.',
'MIXED': '$ must be letters or numbers (no special characters).',
'NAME': '$ must not contain special characters.',
'NOSPACE': '$ must not contain spaces.',
'TRIM': '$ must not start or end with space character.',
'DATE': '$ is not a valid with format YYYY-MM-DD.',
'EMAIL': '$ is not valid.',
'URL': '$ is not valid.',
'PHONE': '$ is not a valid phone number.',
'<': '$ must be less than % characters.',
'<=': '$ must be less or equal to % characters.',
'>': '$ must be greater than % characters.',
'>=': '$ must be greater or equal to % characters.',
'==': '$ must be equal to %',
'!=': '$ must be different than %'
};
/**
* @private
* HTML5 data attributes
*/
var _data = {
validation: 'data-validation',
validationMessage: 'data-validation-message',
regex: 'data-validation-regex',
regexReverse: 'data-validation-regex-reverse',
regexMessage: 'data-validation-regex-message',
group: 'data-validation-group',
label: 'data-validation-label',
errorList: 'data-error-list'
}
/**
* @private
* Default options
*
* @link http://www.runningcoder.org/jqueryvalidation/documentation/
*/
var _options = {
submit: {
settings: {
form: null,
display: "inline",
insertion: "append",
allErrors: false,
trigger: "click",
button: "[type='submit']",
errorClass: "error",
errorListClass: "error-list",
errorListContainer: null,
errorTemplate: null,
inputContainer: null,
clear: "focusin",
scrollToError: false
},
callback: {
onInit: null,
onValidate: null,
onError: null,
onBeforeSubmit: null,
onSubmit: null,
onAfterSubmit: null
}
},
dynamic: {
settings: {
trigger: null,
delay: 300
},
callback: {
onSuccess: null,
onError: null,
onComplete: null
}
},
rules: {},
messages: {},
labels: {},
debug: false
};
/**
* @private
* Limit the supported options on matching keys
*/
var _supported = {
submit: {
settings: {
display: ["inline", "block"],
insertion: ["append", "prepend"], //"before", "insertBefore", "after", "insertAfter"
allErrors: [true, false],
clear: ["focusin", "keypress", false],
trigger: [
"click", "dblclick", "focusout",
"hover", "mousedown", "mouseenter",
"mouseleave", "mousemove", "mouseout",
"mouseover", "mouseup", "toggle"
]
}
},
dynamic: {
settings: {
trigger: ["focusout", "keydown", "keypress", "keyup"]
}
},
debug: [true, false]
};
// =================================================================================================================
/**
* @constructor
* Validation Class
*
* @param {Object} node jQuery form object
* @param {Object} options User defined options
*/
var Validation = function (node, options) {
var errors = [],
messages = {},
formData = {},
delegateSuffix = ".vd", // validation.delegate
resetSuffix = ".vr"; // validation.resetError
window.Validation.hasScrolled = false;
/**
* Extends user-defined "options.message" into the default Validation "_message".
*/
function extendRules() {
options.rules = $.extend(
true,
{},
_rules,
options.rules
);
}
/**
* Extends user-defined "options.message" into the default Validation "_message".
*/
function extendMessages() {
options.messages = $.extend(
true,
{},
_messages,
options.messages
);
}
/**
* Extends user-defined "options" into the default Validation "_options".
* Notes:
* - preventExtensions prevents from modifying the Validation "_options" object structure
* - filter through the "_supported" to delete unsupported "options"
*/
function extendOptions() {
if (!(options instanceof Object)) {
options = {};
}
var tpmOptions = Object.preventExtensions($.extend(true, {}, _options));
for (var method in options) {
if (!options.hasOwnProperty(method) || method === "debug") {
continue;
}
if (~["labels", "messages", "rules"].indexOf(method) && options[method] instanceof Object) {
tpmOptions[method] = options[method];
continue;
}
if (!_options[method] || !(options[method] instanceof Object)) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'extendOptions()',
'arguments': '{' + method + ': ' + JSON.stringify(options[method]) + '}',
'message': 'WARNING - ' + method + ' - invalid option'
});
// {/debug}
continue;
}
for (var type in options[method]) {
if (!options[method].hasOwnProperty(type)) {
continue;
}
if (!_options[method][type] || !(options[method][type] instanceof Object)) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'extendOptions()',
'arguments': '{' + type + ': ' + JSON.stringify(options[method][type]) + '}',
'message': 'WARNING - ' + type + ' - invalid option'
});
// {/debug}
continue;
}
for (var option in options[method][type]) {
if (!options[method][type].hasOwnProperty(option)) {
continue;
}
if (_supported[method] &&
_supported[method][type] &&
_supported[method][type][option] &&
$.inArray(options[method][type][option], _supported[method][type][option]) === -1) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'extendOptions()',
'arguments': '{' + option + ': ' + JSON.stringify(options[method][type][option]) + '}',
'message': 'WARNING - ' + option.toString() + ': ' + JSON.stringify(options[method][type][option]) + ' - unsupported option'
});
// {/debug}
delete options[method][type][option];
}
}
if (tpmOptions[method] && tpmOptions[method][type]) {
tpmOptions[method][type] = $.extend(Object.preventExtensions(tpmOptions[method][type]), options[method][type]);
}
}
}
// {debug}
if (options.debug && $.inArray(options.debug, _supported.debug !== -1)) {
tpmOptions.debug = options.debug;
}
// {/debug}
// @TODO Would there be a better fix to solve event conflict?
if (tpmOptions.dynamic.settings.trigger) {
if (tpmOptions.dynamic.settings.trigger === "keypress" && tpmOptions.submit.settings.clear === "keypress") {
tpmOptions.dynamic.settings.trigger = "keydown";
}
}
options = tpmOptions;
}
/**
* Delegates the dynamic validation on data-validation and data-validation-regex attributes based on trigger.
*
* @returns {Boolean} false if the option is not set
*/
function delegateDynamicValidation() {
if (!options.dynamic.settings.trigger) {
return false;
}
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateDynamicValidation()',
'message': 'OK - Dynamic Validation activated on ' + node.length + ' form(s)'
});
// {/debug}
if (!node.find('[' + _data.validation + '],[' + _data.regex + ']')[0]) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateDynamicValidation()',
'arguments': 'node.find([' + _data.validation + '],[' + _data.regex + '])',
'message': 'ERROR - [' + _data.validation + '] not found'
});
// {/debug}
return false;
}
var event = options.dynamic.settings.trigger + delegateSuffix;
if (options.dynamic.settings.trigger !== "focusout") {
event += " change" + delegateSuffix + " paste" + delegateSuffix;
}
$.each(
node.find('[' + _data.validation + '],[' + _data.regex + ']'),
function (index, input) {
$(input).unbind(event).on(event, function (e) {
if ($(this).is(':disabled')) {
return false;
}
//e.preventDefault();
var input = this,
keyCode = e.keyCode || null;
_typeWatch(function () {
if (!validateInput(input)) {
displayOneError(input.name);
_executeCallback(options.dynamic.callback.onError, [node, input, keyCode, errors[input.name]]);
} else {
_executeCallback(options.dynamic.callback.onSuccess, [node, input, keyCode]);
}
_executeCallback(options.dynamic.callback.onComplete, [node, input, keyCode]);
}, options.dynamic.settings.delay);
});
}
);
}
/**
* Delegates the submit validation on data-validation and data-validation-regex attributes based on trigger.
* Note: Disable the form submit function so the callbacks are not by-passed
*/
function delegateValidation() {
_executeCallback(options.submit.callback.onInit, [node]);
var event = options.submit.settings.trigger + '.vd';
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateValidation()',
'message': 'OK - Validation activated on ' + node.length + ' form(s)'
});
// {/debug}
if (!node.find(options.submit.settings.button)[0]) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateValidation()',
'arguments': '{button: ' + options.submit.settings.button + '}',
'message': 'ERROR - node.find("' + options.submit.settings.button + '") not found'
});
// {/debug}
return false;
}
node.on("submit", false);
node.find(options.submit.settings.button).off('.vd').on(event, function (e) {
e.preventDefault();
resetErrors();
_executeCallback(options.submit.callback.onValidate, [node]);
if (!validateForm()) {
displayErrors();
_executeCallback(options.submit.callback.onError, [node, errors, formData]);
} else {
_executeCallback(options.submit.callback.onBeforeSubmit, [node]);
if (typeof options.submit.callback.onSubmit === "function") {
if (_executeCallback(options.submit.callback.onSubmit, [node, formData]) === true) {
submitForm();
}
} else {
submitForm();
}
_executeCallback(options.submit.callback.onAfterSubmit, [node]);
}
// {debug}
options.debug && window.Debug.print();
// {/debug}
return false;
});
}
/**
* For every "data-validation" & "data-pattern" attributes that are not disabled inside the jQuery "node" object
* the "validateInput" function will be called.
*
* @returns {Boolean} true if no error(s) were found (valid form)
*/
function validateForm() {
var isValid = isEmpty(errors);
formData = {};
$.each(
node.find('input:not([type="submit"]), select, textarea').not(':disabled'),
function(index, input) {
input = $(input);
var value = _getInputValue(input[0]),
inputName = input.attr('name');
if (inputName) {
if (/\[]$/.test(inputName)) {
inputName = inputName.replace(/\[]$/, '');
if (!(formData[inputName] instanceof Array)) {
formData[inputName] = [];
}
formData[inputName].push(value)
} else {
formData[inputName] = value;
}
}
if (!!input.attr(_data.validation) || !!input.attr(_data.regex)) {
if (!validateInput(input[0], value)) {
isValid = false;
}
}
}
);
prepareFormData();
return isValid;
}
/**
* Loop through formData and build an object
*
* @returns {Object} data
*/
function prepareFormData() {
var data = {},
matches,
index;
for (var i in formData) {
if (!formData.hasOwnProperty(i)) continue;
index = 0;
matches = i.split(/\[(.+?)]/g);
var tmpObject = {},
tmpArray = [];
for (var k = matches.length - 1; k >= 0; k--) {
if (matches[k] === "") {
matches.splice(k, 1);
continue;
}
if (tmpArray.length < 1) {
tmpObject[matches[k]] = Number(formData[i]) || formData[i];
} else {
tmpObject = {};
tmpObject[matches[k]] = tmpArray[tmpArray.length - 1];
}
tmpArray.push(tmpObject)
}
data = $.extend(true, data, tmpObject);
}
formData = data;
}
/**
* Prepare the information from the data attributes
* and call the "validateRule" function.
*
* @param {Object} input Reference of the input element
*
* @returns {Boolean} true if no error(s) were found (valid input)
*/
function validateInput(input, value) {
var inputName = $(input).attr('name'),
value = value || _getInputValue(input);
if (!inputName) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateInput()',
'arguments': '$(input).attr("name")',
'message': 'ERROR - Missing input [name]'
});
// {/debug}
return false;
}
var matches = inputName.replace(/]$/, '').split(/]\[|[[\]]/g),
inputShortName = window.Validation.labels[inputName] ||
options.labels[inputName] ||
$(input).attr(_data.label) ||
matches[matches.length - 1],
validationArray = $(input).attr(_data.validation),
validationMessage = $(input).attr(_data.validationMessage),
validationRegex = $(input).attr(_data.regex),
validationRegexReverse = !($(input).attr(_data.regexReverse) === undefined),
validationRegexMessage = $(input).attr(_data.regexMessage),
validateOnce = false;
if (validationArray) {
validationArray = _api._splitValidation(validationArray);
}
// Validates the "data-validation"
if (validationArray instanceof Array && validationArray.length > 0) {
// "OPTIONAL" input will not be validated if it's empty
if ($.trim(value) === '' && ~validationArray.indexOf('OPTIONAL')) {
return true;
}
$.each(validationArray, function (i, rule) {
if (validateOnce === true) {
return true;
}
try {
validateRule(value, rule);
} catch (error) {
if (validationMessage || !options.submit.settings.allErrors) {
validateOnce = true;
}
error[0] = validationMessage || error[0];
registerError(inputName, error[0].replace('$', inputShortName).replace('%', error[1]));
}
});
}
// Validates the "data-validation-regex"
if (validationRegex) {
var rule = _buildRegexFromString(validationRegex);
// Do not block validation if a regexp is bad, only skip it
if (!(rule instanceof RegExp)) {
return true;
}
try {
validateRule(value, rule, validationRegexReverse);
} catch (error) {
error[0] = validationRegexMessage || error[0];
registerError(inputName, error[0].replace('$', inputShortName));
}
}
return !errors[inputName] || errors[inputName] instanceof Array && errors[inputName].length === 0;
}
/**
* Validate an input value against one rule.
* If a "value-rule" mismatch occurs, an error is thrown to the caller function.
*
* @param {String} value
* @param {*} rule
* @param {Boolean} [reversed]
*
* @returns {*} Error if a mismatch occurred.
*/
function validateRule(value, rule, reversed) {
// Validate for "data-validation-regex" and "data-validation-regex-reverse"
if (rule instanceof RegExp) {
var isValid = rule.test(value);
if (reversed) {
isValid = !isValid;
}
if (!isValid) {
throw [options.messages['default'], ''];
}
return;
}
if (options.rules[rule]) {
if (!options.rules[rule].test(value)) {
throw [options.messages[rule], ''];
}
return;
}
// Validate for comparison "data-validation"
var comparison = rule.match(options.rules.COMPARISON);
if (!comparison || comparison.length !== 4) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'value: ' + value + ' rule: ' + rule,
'message': 'WARNING - Invalid comparison'
});
// {/debug}
return;
}
var type = comparison[1],
operator = comparison[2],
compared = comparison[3],
comparedValue;
switch (type) {
// Compare input "Length"
case "L":
// Only numeric value for "L" are allowed
if (isNaN(compared)) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'compare: ' + compared + ' rule: ' + rule,
'message': 'WARNING - Invalid rule, "L" compare must be numeric'
});
// {/debug}
return false;
} else {
if (!value || eval(value.length + operator + parseFloat(compared)) === false) {
throw [options.messages[operator], compared];
}
}
break;
// Compare input "Value"
case "V":
default:
// Compare Field values
if (isNaN(compared)) {
comparedValue = node.find('[name="' + compared + '"]').val();
if (!comparedValue) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'compare: ' + compared + ' rule: ' + rule,
'message': 'WARNING - Unable to find compared field [name="' + compared + '"]'
});
// {/debug}
return false;
}
if (!value || !eval('"' + encodeURIComponent(value) + '"' + operator + '"' + encodeURIComponent(comparedValue) + '"')) {
throw [options.messages[operator].replace(' characters', ''), compared];
}
} else {
// Compare numeric value
if (!value || isNaN(value) || !eval(value + operator + parseFloat(compared))) {
throw [options.messages[operator].replace(' characters', ''), compared];
}
}
break;
}
}
/**
* Register an error into the global "error" variable.
*
* @param {String} inputName Input where the error occurred
* @param {String} error Description of the error to be displayed
*/
function registerError(inputName, error) {
if (!errors[inputName]) {
errors[inputName] = [];
}
error = error.capitalize();
var hasError = false;
for (var i = 0; i < errors[inputName].length; i++) {
if (errors[inputName][i] === error) {
hasError = true;
break;
}
}
if (!hasError) {
errors[inputName].push(error);
}
}
/**
* Display a single error based on "inputName" key inside the "errors" global array.
* The input, the label and the "inputContainer" will be given the "errorClass" and other
* settings will be considered.
*
* @param {String} inputName Key used for search into "errors"
*
* @returns {Boolean} false if an unwanted behavior occurs
*/
function displayOneError(inputName) {
var input,
inputId,
errorContainer,
label,
html = '<div class="' + options.submit.settings.errorListClass + '" ' + _data.errorList + '><ul></ul></div>',
group,
groupInput;
if (!errors.hasOwnProperty(inputName)) {
return false;
}
input = node.find('[name="' + inputName + '"]');
label = null;
if (!input[0]) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'displayOneError()',
'arguments': '[name="' + inputName + '"]',
'message': 'ERROR - Unable to find input by name "' + inputName + '"'
});
// {/debug}
return false;
}
group = input.attr(_data.group);
if (group) {
groupInput = node.find('[name="' + inputName + '"]');
label = node.find('[id="' + group + '"]');
if (label[0]) {
label.addClass(options.submit.settings.errorClass);
errorContainer = label;
}
//node.find('[' + _data.group + '="' + group + '"]').addClass(options.submit.settings.errorClass)
} else {
input.addClass(options.submit.settings.errorClass);
if (options.submit.settings.inputContainer) {
input.parentsUntil(node, options.submit.settings.inputContainer).addClass(options.submit.settings.errorClass);
}
inputId = input.attr('id');
if (inputId) {
label = node.find('label[for="' + inputId + '"]')[0];
}
if (!label) {
label = input.parentsUntil(node, 'label')[0];
}
if (label) {
label = $(label);
label.addClass(options.submit.settings.errorClass);
}
}
if (options.submit.settings.display === 'inline') {
if (options.submit.settings.errorListContainer) {
errorContainer = input.parentsUntil(node, options.submit.settings.errorListContainer);
} else {
errorContainer = errorContainer || input.parent();
}
} else if (options.submit.settings.display === 'block') {
errorContainer = node;
}
// Prevent double error list if the previous one has not been cleared.
if (options.submit.settings.display === 'inline' && errorContainer.find('[' + _data.errorList + ']')[0]) {
return false;
}
if (options.submit.settings.display === "inline" ||
(options.submit.settings.display === "block" && !errorContainer.find('[' + _data.errorList + ']')[0])
) {
if (options.submit.settings.insertion === 'append') {
errorContainer.append(html);
} else if (options.submit.settings.insertion === 'prepend') {
errorContainer.prepend(html);
}
}
for (var i = 0; i < errors[inputName].length; i++) {
if (options.submit.settings.errorTemplate) {
errorContainer.find('[' + _data.errorList + '] ul')
.append('<li>' + options.submit.settings.errorTemplate.replace('{{validation-message}}', errors[inputName][i]) + '</li>');
} else {
errorContainer.find('[' + _data.errorList + '] ul').append('<li>' + errors[inputName][i] + '</li>');
}
}
if (options.submit.settings.clear || options.dynamic.settings.trigger) {
if (group && groupInput) {
input = groupInput;
}
var event = "coucou" + resetSuffix;
if (options.submit.settings.clear) {
event += " " + options.submit.settings.clear + resetSuffix;
if (~['radio', 'checkbox'].indexOf(input[0].type)) {
event += " change" + resetSuffix;
}
}
if (options.dynamic.settings.trigger) {
event += " " + options.dynamic.settings.trigger + resetSuffix;
if (options.dynamic.settings.trigger !== "focusout" && !~['radio', 'checkbox'].indexOf(input[0].type)) {
event += " change" + resetSuffix + " paste" + resetSuffix;
}
}
input.unbind(event).on(event, function (a, b, c, d, e) {
return function () {
if (e) {
if ($(c).hasClass(options.submit.settings.errorClass)) {
resetOneError(a, b, c, d, e);
}
} else if ($(b).hasClass(options.submit.settings.errorClass)) {
resetOneError(a, b, c, d);
}
};
}(inputName, input, label, errorContainer, group));
}
if (options.submit.settings.scrollToError && !window.Validation.hasScrolled) {
window.Validation.hasScrolled = true;
var offset = parseFloat(options.submit.settings.scrollToError.offset) || 0,
duration = parseFloat(options.submit.settings.scrollToError.duration) || 500,
handle = (options.submit.settings.display === 'block') ? errorContainer : input;
$('html, body').animate({
scrollTop: handle.offset().top + offset
}, duration);
}
}
/**
* Display all of the errors
*/
function displayErrors() {
for (var inputName in errors) {
if (!errors.hasOwnProperty(inputName)) continue;
displayOneError(inputName);
}
}
/**
* Remove an input error.
*
* @param {String} inputName Key reference to delete the error from "errors" global variable
* @param {Object} input jQuery object of the input
* @param {Object} label jQuery object of the input's label
* @param {Object} container jQuery object of the "errorList"
* @param {String} [group] Name of the group if any (ex: used on input radio)
*/
function resetOneError(inputName, input, label, container, group) {
delete errors[inputName];