-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparsley.min.js
2446 lines (1972 loc) · 90.2 KB
/
parsley.min.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
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
/*!
* Parsley.js
* Version 2.7.0 - built Wed, Mar 1st 2017, 3:53 pm
* http://parsleyjs.org
* Guillaume Potier - <guillaume@wisembly.com>
* Marc-Andre Lafortune - <petroselinum@marc-andre.ca>
* MIT Licensed
*/
// The source code below is generated by babel as
// Parsley is written in ECMAScript 6
//
var _slice = Array.prototype.slice;
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : global.parsley = factory(global.jQuery);
})(this, function ($) {
'use strict';
var globalID = 1;
var pastWarnings = {};
var Utils__Utils = {
// Parsley DOM-API
// returns object from dom attributes and values
attr: function attr($element, namespace, obj) {
var i;
var attribute;
var attributes;
var regex = new RegExp('^' + namespace, 'i');
if ('undefined' === typeof obj) obj = {};else {
// Clear all own properties. This won't affect prototype's values
for (i in obj) {
if (obj.hasOwnProperty(i)) delete obj[i];
}
}
if ('undefined' === typeof $element || 'undefined' === typeof $element[0]) return obj;
attributes = $element[0].attributes;
for (i = attributes.length; i--;) {
attribute = attributes[i];
if (attribute && attribute.specified && regex.test(attribute.name)) {
obj[this.camelize(attribute.name.slice(namespace.length))] = this.deserializeValue(attribute.value);
}
}
return obj;
},
checkAttr: function checkAttr($element, namespace, _checkAttr) {
return $element.is('[' + namespace + _checkAttr + ']');
},
setAttr: function setAttr($element, namespace, attr, value) {
$element[0].setAttribute(this.dasherize(namespace + attr), String(value));
},
generateID: function generateID() {
return '' + globalID++;
},
/** Third party functions **/
// Zepto deserialize function
deserializeValue: function deserializeValue(value) {
var num;
try {
return value ? value == "true" || (value == "false" ? false : value == "null" ? null : !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value) : value;
} catch (e) {
return value;
}
},
// Zepto camelize function
camelize: function camelize(str) {
return str.replace(/-+(.)?/g, function (match, chr) {
return chr ? chr.toUpperCase() : '';
});
},
// Zepto dasherize function
dasherize: function dasherize(str) {
return str.replace(/::/g, '/').replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').replace(/_/g, '-').toLowerCase();
},
warn: function warn() {
var _window$console;
if (window.console && 'function' === typeof window.console.warn) (_window$console = window.console).warn.apply(_window$console, arguments);
},
warnOnce: function warnOnce(msg) {
if (!pastWarnings[msg]) {
pastWarnings[msg] = true;
this.warn.apply(this, arguments);
}
},
_resetWarnings: function _resetWarnings() {
pastWarnings = {};
},
trimString: function trimString(string) {
return string.replace(/^\s+|\s+$/g, '');
},
parse: {
date: function date(string) {
var parsed = string.match(/^(\d{4,})-(\d\d)-(\d\d)$/);
if (!parsed) return null;
var _parsed$map = parsed.map(function (x) {
return parseInt(x, 10);
});
var _parsed$map2 = _slicedToArray(_parsed$map, 4);
var _ = _parsed$map2[0];
var year = _parsed$map2[1];
var month = _parsed$map2[2];
var day = _parsed$map2[3];
var date = new Date(year, month - 1, day);
if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) return null;
return date;
},
string: function string(_string) {
return _string;
},
integer: function integer(string) {
if (isNaN(string)) return null;
return parseInt(string, 10);
},
number: function number(string) {
if (isNaN(string)) throw null;
return parseFloat(string);
},
'boolean': function _boolean(string) {
return !/^\s*false\s*$/i.test(string);
},
object: function object(string) {
return Utils__Utils.deserializeValue(string);
},
regexp: function regexp(_regexp) {
var flags = '';
// Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern
if (/^\/.*\/(?:[gimy]*)$/.test(_regexp)) {
// Replace the regexp literal string with the first match group: ([gimy]*)
// If no flag is present, this will be a blank string
flags = _regexp.replace(/.*\/([gimy]*)$/, '$1');
// Again, replace the regexp literal string with the first match group:
// everything excluding the opening and closing slashes and the flags
_regexp = _regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1');
} else {
// Anchor regexp:
_regexp = '^' + _regexp + '$';
}
return new RegExp(_regexp, flags);
}
},
parseRequirement: function parseRequirement(requirementType, string) {
var converter = this.parse[requirementType || 'string'];
if (!converter) throw 'Unknown requirement specification: "' + requirementType + '"';
var converted = converter(string);
if (converted === null) throw 'Requirement is not a ' + requirementType + ': "' + string + '"';
return converted;
},
namespaceEvents: function namespaceEvents(events, namespace) {
events = this.trimString(events || '').split(/\s+/);
if (!events[0]) return '';
return $.map(events, function (evt) {
return evt + '.' + namespace;
}).join(' ');
},
difference: function difference(array, remove) {
// This is O(N^2), should be optimized
var result = [];
$.each(array, function (_, elem) {
if (remove.indexOf(elem) == -1) result.push(elem);
});
return result;
},
// Alter-ego to native Promise.all, but for jQuery
all: function all(promises) {
// jQuery treats $.when() and $.when(singlePromise) differently; let's avoid that and add spurious elements
return $.when.apply($, _toConsumableArray(promises).concat([42, 42]));
},
// Object.create polyfill, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill
objectCreate: Object.create || (function () {
var Object = function Object() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype != 'object') {
throw TypeError('Argument must be an object');
}
Object.prototype = prototype;
var result = new Object();
Object.prototype = null;
return result;
};
})(),
_SubmitSelector: 'input[type="submit"], button:submit'
};
var Utils__default = Utils__Utils;
// All these options could be overriden and specified directly in DOM using
// `data-parsley-` default DOM-API
// eg: `inputs` can be set in DOM using `data-parsley-inputs="input, textarea"`
// eg: `data-parsley-stop-on-first-failing-constraint="false"`
var Defaults = {
// ### General
// Default data-namespace for DOM API
namespace: 'data-parsley-',
// Supported inputs by default
inputs: 'input, textarea, select',
// Excluded inputs by default
excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]',
// Stop validating field on highest priority failing constraint
priorityEnabled: true,
// ### Field only
// identifier used to group together inputs (e.g. radio buttons...)
multiple: null,
// identifier (or array of identifiers) used to validate only a select group of inputs
group: null,
// ### UI
// Enable\Disable error messages
uiEnabled: true,
// Key events threshold before validation
validationThreshold: 3,
// Focused field on form validation error. 'first'|'last'|'none'
focus: 'first',
// event(s) that will trigger validation before first failure. eg: `input`...
trigger: false,
// event(s) that will trigger validation after first failure.
triggerAfterFailure: 'input',
// Class that would be added on every failing validation Parsley field
errorClass: 'parsley-error',
// Same for success validation
successClass: 'parsley-success',
// Return the `$element` that will receive these above success or error classes
// Could also be (and given directly from DOM) a valid selector like `'#div'`
classHandler: function classHandler(Field) {},
// Return the `$element` where errors will be appended
// Could also be (and given directly from DOM) a valid selector like `'#div'`
errorsContainer: function errorsContainer(Field) {},
// ul elem that would receive errors' list
errorsWrapper: '<ul class="parsley-errors-list"></ul>',
// li elem that would receive error message
errorTemplate: '<li></li>'
};
var Base = function Base() {
this.__id__ = Utils__default.generateID();
};
Base.prototype = {
asyncSupport: true, // Deprecated
_pipeAccordingToValidationResult: function _pipeAccordingToValidationResult() {
var _this = this;
var pipe = function pipe() {
var r = $.Deferred();
if (true !== _this.validationResult) r.reject();
return r.resolve().promise();
};
return [pipe, pipe];
},
actualizeOptions: function actualizeOptions() {
Utils__default.attr(this.$element, this.options.namespace, this.domOptions);
if (this.parent && this.parent.actualizeOptions) this.parent.actualizeOptions();
return this;
},
_resetOptions: function _resetOptions(initOptions) {
this.domOptions = Utils__default.objectCreate(this.parent.options);
this.options = Utils__default.objectCreate(this.domOptions);
// Shallow copy of ownProperties of initOptions:
for (var i in initOptions) {
if (initOptions.hasOwnProperty(i)) this.options[i] = initOptions[i];
}
this.actualizeOptions();
},
_listeners: null,
// Register a callback for the given event name
// Callback is called with context as the first argument and the `this`
// The context is the current parsley instance, or window.Parsley if global
// A return value of `false` will interrupt the calls
on: function on(name, fn) {
this._listeners = this._listeners || {};
var queue = this._listeners[name] = this._listeners[name] || [];
queue.push(fn);
return this;
},
// Deprecated. Use `on` instead
subscribe: function subscribe(name, fn) {
$.listenTo(this, name.toLowerCase(), fn);
},
// Unregister a callback (or all if none is given) for the given event name
off: function off(name, fn) {
var queue = this._listeners && this._listeners[name];
if (queue) {
if (!fn) {
delete this._listeners[name];
} else {
for (var i = queue.length; i--;) if (queue[i] === fn) queue.splice(i, 1);
}
}
return this;
},
// Deprecated. Use `off`
unsubscribe: function unsubscribe(name, fn) {
$.unsubscribeTo(this, name.toLowerCase());
},
// Trigger an event of the given name
// A return value of `false` interrupts the callback chain
// Returns false if execution was interrupted
trigger: function trigger(name, target, extraArg) {
target = target || this;
var queue = this._listeners && this._listeners[name];
var result;
var parentResult;
if (queue) {
for (var i = queue.length; i--;) {
result = queue[i].call(target, target, extraArg);
if (result === false) return result;
}
}
if (this.parent) {
return this.parent.trigger(name, target, extraArg);
}
return true;
},
asyncIsValid: function asyncIsValid(group, force) {
Utils__default.warnOnce("asyncIsValid is deprecated; please use whenValid instead");
return this.whenValid({ group: group, force: force });
},
_findRelated: function _findRelated() {
return this.options.multiple ? this.parent.$element.find('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]') : this.$element;
}
};
var convertArrayRequirement = function convertArrayRequirement(string, length) {
var m = string.match(/^\s*\[(.*)\]\s*$/);
if (!m) throw 'Requirement is not an array: "' + string + '"';
var values = m[1].split(',').map(Utils__default.trimString);
if (values.length !== length) throw 'Requirement has ' + values.length + ' values when ' + length + ' are needed';
return values;
};
var convertExtraOptionRequirement = function convertExtraOptionRequirement(requirementSpec, string, extraOptionReader) {
var main = null;
var extra = {};
for (var key in requirementSpec) {
if (key) {
var value = extraOptionReader(key);
if ('string' === typeof value) value = Utils__default.parseRequirement(requirementSpec[key], value);
extra[key] = value;
} else {
main = Utils__default.parseRequirement(requirementSpec[key], string);
}
}
return [main, extra];
};
// A Validator needs to implement the methods `validate` and `parseRequirements`
var Validator = function Validator(spec) {
$.extend(true, this, spec);
};
Validator.prototype = {
// Returns `true` iff the given `value` is valid according the given requirements.
validate: function validate(value, requirementFirstArg) {
if (this.fn) {
// Legacy style validator
if (arguments.length > 3) // If more args then value, requirement, instance...
requirementFirstArg = [].slice.call(arguments, 1, -1); // Skip first arg (value) and last (instance), combining the rest
return this.fn(value, requirementFirstArg);
}
if ($.isArray(value)) {
if (!this.validateMultiple) throw 'Validator `' + this.name + '` does not handle multiple values';
return this.validateMultiple.apply(this, arguments);
} else {
var instance = arguments[arguments.length - 1];
if (this.validateDate && instance._isDateInput()) {
arguments[0] = Utils__default.parse.date(arguments[0]);
if (arguments[0] === null) return false;
return this.validateDate.apply(this, arguments);
}
if (this.validateNumber) {
if (isNaN(value)) return false;
arguments[0] = parseFloat(arguments[0]);
return this.validateNumber.apply(this, arguments);
}
if (this.validateString) {
return this.validateString.apply(this, arguments);
}
throw 'Validator `' + this.name + '` only handles multiple values';
}
},
// Parses `requirements` into an array of arguments,
// according to `this.requirementType`
parseRequirements: function parseRequirements(requirements, extraOptionReader) {
if ('string' !== typeof requirements) {
// Assume requirement already parsed
// but make sure we return an array
return $.isArray(requirements) ? requirements : [requirements];
}
var type = this.requirementType;
if ($.isArray(type)) {
var values = convertArrayRequirement(requirements, type.length);
for (var i = 0; i < values.length; i++) values[i] = Utils__default.parseRequirement(type[i], values[i]);
return values;
} else if ($.isPlainObject(type)) {
return convertExtraOptionRequirement(type, requirements, extraOptionReader);
} else {
return [Utils__default.parseRequirement(type, requirements)];
}
},
// Defaults:
requirementType: 'string',
priority: 2
};
var ValidatorRegistry = function ValidatorRegistry(validators, catalog) {
this.__class__ = 'ValidatorRegistry';
// Default Parsley locale is en
this.locale = 'en';
this.init(validators || {}, catalog || {});
};
var typeTesters = {
email: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\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])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,
// Follow https://www.w3.org/TR/html5/infrastructure.html#floating-point-numbers
number: /^-?(\d*\.)?\d+(e[-+]?\d+)?$/i,
integer: /^-?\d+$/,
digits: /^\d+$/,
alphanum: /^\w+$/i,
date: {
test: function test(value) {
return Utils__default.parse.date(value) !== null;
}
},
url: new RegExp("^" +
// protocol identifier
"(?:(?:https?|ftp)://)?" + // ** mod: make scheme optional
// user:pass authentication
"(?:\\S+(?::\\S*)?@)?" + "(?:" +
// IP address exclusion
// private & local networks
// "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + // ** mod: allow local networks
// "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks
// "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" +
// host name
'(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' +
// domain name
'(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' +
// TLD identifier
'(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))' + ")" +
// port number
"(?::\\d{2,5})?" +
// resource path
"(?:/\\S*)?" + "$", 'i')
};
typeTesters.range = typeTesters.number;
// See http://stackoverflow.com/a/10454560/8279
var decimalPlaces = function decimalPlaces(num) {
var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) {
return 0;
}
return Math.max(0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0) - (
// Adjust for scientific notation.
match[2] ? +match[2] : 0));
};
// parseArguments('number', ['1', '2']) => [1, 2]
var ValidatorRegistry__parseArguments = function ValidatorRegistry__parseArguments(type, args) {
return args.map(Utils__default.parse[type]);
};
// operatorToValidator returns a validating function for an operator function, applied to the given type
var ValidatorRegistry__operatorToValidator = function ValidatorRegistry__operatorToValidator(type, operator) {
return function (value) {
for (var _len = arguments.length, requirementsAndInput = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
requirementsAndInput[_key - 1] = arguments[_key];
}
requirementsAndInput.pop(); // Get rid of `input` argument
return operator.apply(undefined, [value].concat(_toConsumableArray(ValidatorRegistry__parseArguments(type, requirementsAndInput))));
};
};
var ValidatorRegistry__comparisonOperator = function ValidatorRegistry__comparisonOperator(operator) {
return {
validateDate: ValidatorRegistry__operatorToValidator('date', operator),
validateNumber: ValidatorRegistry__operatorToValidator('number', operator),
requirementType: operator.length <= 2 ? 'string' : ['string', 'string'], // Support operators with a 1 or 2 requirement(s)
priority: 30
};
};
ValidatorRegistry.prototype = {
init: function init(validators, catalog) {
this.catalog = catalog;
// Copy prototype's validators:
this.validators = $.extend({}, this.validators);
for (var name in validators) this.addValidator(name, validators[name].fn, validators[name].priority);
window.Parsley.trigger('parsley:validator:init');
},
// Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n
setLocale: function setLocale(locale) {
if ('undefined' === typeof this.catalog[locale]) throw new Error(locale + ' is not available in the catalog');
this.locale = locale;
return this;
},
// Add a new messages catalog for a given locale. Set locale for this catalog if set === `true`
addCatalog: function addCatalog(locale, messages, set) {
if ('object' === typeof messages) this.catalog[locale] = messages;
if (true === set) return this.setLocale(locale);
return this;
},
// Add a specific message for a given constraint in a given locale
addMessage: function addMessage(locale, name, message) {
if ('undefined' === typeof this.catalog[locale]) this.catalog[locale] = {};
this.catalog[locale][name] = message;
return this;
},
// Add messages for a given locale
addMessages: function addMessages(locale, nameMessageObject) {
for (var name in nameMessageObject) this.addMessage(locale, name, nameMessageObject[name]);
return this;
},
// Add a new validator
//
// addValidator('custom', {
// requirementType: ['integer', 'integer'],
// validateString: function(value, from, to) {},
// priority: 22,
// messages: {
// en: "Hey, that's no good",
// fr: "Aye aye, pas bon du tout",
// }
// })
//
// Old API was addValidator(name, function, priority)
//
addValidator: function addValidator(name, arg1, arg2) {
if (this.validators[name]) Utils__default.warn('Validator "' + name + '" is already defined.');else if (Defaults.hasOwnProperty(name)) {
Utils__default.warn('"' + name + '" is a restricted keyword and is not a valid validator name.');
return;
}
return this._setValidator.apply(this, arguments);
},
updateValidator: function updateValidator(name, arg1, arg2) {
if (!this.validators[name]) {
Utils__default.warn('Validator "' + name + '" is not already defined.');
return this.addValidator.apply(this, arguments);
}
return this._setValidator.apply(this, arguments);
},
removeValidator: function removeValidator(name) {
if (!this.validators[name]) Utils__default.warn('Validator "' + name + '" is not defined.');
delete this.validators[name];
return this;
},
_setValidator: function _setValidator(name, validator, priority) {
if ('object' !== typeof validator) {
// Old style validator, with `fn` and `priority`
validator = {
fn: validator,
priority: priority
};
}
if (!validator.validate) {
validator = new Validator(validator);
}
this.validators[name] = validator;
for (var locale in validator.messages || {}) this.addMessage(locale, name, validator.messages[locale]);
return this;
},
getErrorMessage: function getErrorMessage(constraint) {
var message;
// Type constraints are a bit different, we have to match their requirements too to find right error message
if ('type' === constraint.name) {
var typeMessages = this.catalog[this.locale][constraint.name] || {};
message = typeMessages[constraint.requirements];
} else message = this.formatMessage(this.catalog[this.locale][constraint.name], constraint.requirements);
return message || this.catalog[this.locale].defaultMessage || this.catalog.en.defaultMessage;
},
// Kind of light `sprintf()` implementation
formatMessage: function formatMessage(string, parameters) {
if ('object' === typeof parameters) {
for (var i in parameters) string = this.formatMessage(string, parameters[i]);
return string;
}
return 'string' === typeof string ? string.replace(/%s/i, parameters) : '';
},
// Here is the Parsley default validators list.
// A validator is an object with the following key values:
// - priority: an integer
// - requirement: 'string' (default), 'integer', 'number', 'regexp' or an Array of these
// - validateString, validateMultiple, validateNumber: functions returning `true`, `false` or a promise
// Alternatively, a validator can be a function that returns such an object
//
validators: {
notblank: {
validateString: function validateString(value) {
return (/\S/.test(value)
);
},
priority: 2
},
required: {
validateMultiple: function validateMultiple(values) {
return values.length > 0;
},
validateString: function validateString(value) {
return (/\S/.test(value)
);
},
priority: 512
},
type: {
validateString: function validateString(value, type) {
var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var _ref$step = _ref.step;
var step = _ref$step === undefined ? 'any' : _ref$step;
var _ref$base = _ref.base;
var base = _ref$base === undefined ? 0 : _ref$base;
var tester = typeTesters[type];
if (!tester) {
throw new Error('validator type `' + type + '` is not supported');
}
if (!tester.test(value)) return false;
if ('number' === type) {
if (!/^any$/i.test(step || '')) {
var nb = Number(value);
var decimals = Math.max(decimalPlaces(step), decimalPlaces(base));
if (decimalPlaces(nb) > decimals) // Value can't have too many decimals
return false;
// Be careful of rounding errors by using integers.
var toInt = function toInt(f) {
return Math.round(f * Math.pow(10, decimals));
};
if ((toInt(nb) - toInt(base)) % toInt(step) != 0) return false;
}
}
return true;
},
requirementType: {
'': 'string',
step: 'string',
base: 'number'
},
priority: 256
},
pattern: {
validateString: function validateString(value, regexp) {
return regexp.test(value);
},
requirementType: 'regexp',
priority: 64
},
minlength: {
validateString: function validateString(value, requirement) {
return value.length >= requirement;
},
requirementType: 'integer',
priority: 30
},
maxlength: {
validateString: function validateString(value, requirement) {
return value.length <= requirement;
},
requirementType: 'integer',
priority: 30
},
length: {
validateString: function validateString(value, min, max) {
return value.length >= min && value.length <= max;
},
requirementType: ['integer', 'integer'],
priority: 30
},
mincheck: {
validateMultiple: function validateMultiple(values, requirement) {
return values.length >= requirement;
},
requirementType: 'integer',
priority: 30
},
maxcheck: {
validateMultiple: function validateMultiple(values, requirement) {
return values.length <= requirement;
},
requirementType: 'integer',
priority: 30
},
check: {
validateMultiple: function validateMultiple(values, min, max) {
return values.length >= min && values.length <= max;
},
requirementType: ['integer', 'integer'],
priority: 30
},
min: ValidatorRegistry__comparisonOperator(function (value, requirement) {
return value >= requirement;
}),
max: ValidatorRegistry__comparisonOperator(function (value, requirement) {
return value <= requirement;
}),
range: ValidatorRegistry__comparisonOperator(function (value, min, max) {
return value >= min && value <= max;
}),
equalto: {
validateString: function validateString(value, refOrValue) {
var $reference = $(refOrValue);
if ($reference.length) return value === $reference.val();else return value === refOrValue;
},
priority: 256
}
}
};
var UI = {};
var diffResults = function diffResults(newResult, oldResult, deep) {
var added = [];
var kept = [];
for (var i = 0; i < newResult.length; i++) {
var found = false;
for (var j = 0; j < oldResult.length; j++) if (newResult[i].assert.name === oldResult[j].assert.name) {
found = true;
break;
}
if (found) kept.push(newResult[i]);else added.push(newResult[i]);
}
return {
kept: kept,
added: added,
removed: !deep ? diffResults(oldResult, newResult, true).added : []
};
};
UI.Form = {
_actualizeTriggers: function _actualizeTriggers() {
var _this2 = this;
this.$element.on('submit.Parsley', function (evt) {
_this2.onSubmitValidate(evt);
});
this.$element.on('click.Parsley', Utils__default._SubmitSelector, function (evt) {
_this2.onSubmitButton(evt);
});
// UI could be disabled
if (false === this.options.uiEnabled) return;
this.$element.attr('novalidate', '');
},
focus: function focus() {
this._focusedField = null;
if (true === this.validationResult || 'none' === this.options.focus) return null;
for (var i = 0; i < this.fields.length; i++) {
var field = this.fields[i];
if (true !== field.validationResult && field.validationResult.length > 0 && 'undefined' === typeof field.options.noFocus) {
this._focusedField = field.$element;
if ('first' === this.options.focus) break;
}
}
if (null === this._focusedField) return null;
return this._focusedField.focus();
},
_destroyUI: function _destroyUI() {
// Reset all event listeners
this.$element.off('.Parsley');
}
};
UI.Field = {
_reflowUI: function _reflowUI() {
this._buildUI();
// If this field doesn't have an active UI don't bother doing something
if (!this._ui) return;
// Diff between two validation results
var diff = diffResults(this.validationResult, this._ui.lastValidationResult);
// Then store current validation result for next reflow
this._ui.lastValidationResult = this.validationResult;
// Handle valid / invalid / none field class
this._manageStatusClass();
// Add, remove, updated errors messages
this._manageErrorsMessages(diff);
// Triggers impl
this._actualizeTriggers();
// If field is not valid for the first time, bind keyup trigger to ease UX and quickly inform user
if ((diff.kept.length || diff.added.length) && !this._failedOnce) {
this._failedOnce = true;
this._actualizeTriggers();
}
},
// Returns an array of field's error message(s)
getErrorsMessages: function getErrorsMessages() {
// No error message, field is valid
if (true === this.validationResult) return [];
var messages = [];
for (var i = 0; i < this.validationResult.length; i++) messages.push(this.validationResult[i].errorMessage || this._getErrorMessage(this.validationResult[i].assert));
return messages;
},
// It's a goal of Parsley that this method is no longer required [#1073]
addError: function addError(name) {
var _ref2 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var message = _ref2.message;
var assert = _ref2.assert;
var _ref2$updateClass = _ref2.updateClass;
var updateClass = _ref2$updateClass === undefined ? true : _ref2$updateClass;
this._buildUI();
this._addError(name, { message: message, assert: assert });
if (updateClass) this._errorClass();
},
// It's a goal of Parsley that this method is no longer required [#1073]
updateError: function updateError(name) {
var _ref3 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var message = _ref3.message;
var assert = _ref3.assert;
var _ref3$updateClass = _ref3.updateClass;
var updateClass = _ref3$updateClass === undefined ? true : _ref3$updateClass;
this._buildUI();
this._updateError(name, { message: message, assert: assert });
if (updateClass) this._errorClass();
},
// It's a goal of Parsley that this method is no longer required [#1073]
removeError: function removeError(name) {
var _ref4 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref4$updateClass = _ref4.updateClass;
var updateClass = _ref4$updateClass === undefined ? true : _ref4$updateClass;
this._buildUI();
this._removeError(name);
// edge case possible here: remove a standard Parsley error that is still failing in this.validationResult
// but highly improbable cuz' manually removing a well Parsley handled error makes no sense.
if (updateClass) this._manageStatusClass();
},
_manageStatusClass: function _manageStatusClass() {
if (this.hasConstraints() && this.needsValidation() && true === this.validationResult) this._successClass();else if (this.validationResult.length > 0) this._errorClass();else this._resetClass();
},
_manageErrorsMessages: function _manageErrorsMessages(diff) {
if ('undefined' !== typeof this.options.errorsMessagesDisabled) return;
// Case where we have errorMessage option that configure an unique field error message, regardless failing validators
if ('undefined' !== typeof this.options.errorMessage) {
if (diff.added.length || diff.kept.length) {
this._insertErrorWrapper();
if (0 === this._ui.$errorsWrapper.find('.parsley-custom-error-message').length) this._ui.$errorsWrapper.append($(this.options.errorTemplate).addClass('parsley-custom-error-message'));
return this._ui.$errorsWrapper.addClass('filled').find('.parsley-custom-error-message').html(this.options.errorMessage);
}
return this._ui.$errorsWrapper.removeClass('filled').find('.parsley-custom-error-message').remove();
}
// Show, hide, update failing constraints messages
for (var i = 0; i < diff.removed.length; i++) this._removeError(diff.removed[i].assert.name);