This repository was archived by the owner on Jul 1, 2020. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathangular-validation.js
More file actions
3378 lines (3072 loc) · 156 KB
/
Copy pathangular-validation.js
File metadata and controls
3378 lines (3072 loc) · 156 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
/**
* Angular-Validation Directive and Service (ghiscoding)
* http://github.com/ghiscoding/angular-validation
* @author: Ghislain B.
* @version: 1.5.28
* @license: MIT
* @build: Thu Jun 20 2019 21:18:15 GMT-0400 (Eastern Daylight Time)
*/
/**
* Angular-Validation Directive (ghiscoding)
* https://github.com/ghiscoding/angular-validation
*
* @author: Ghislain B.
* @started: 2014-02-04
*
* @desc: If a field becomes invalid, the text inside the error <span> or <div> will show up because the error string gets filled
* Though when the field becomes valid then the error message becomes an empty string,
* it will be transparent to the user even though the <span> still exist but becomes invisible since the text is empty.
*
*/
angular
.module('ghiscoding.validation', ['pascalprecht.translate'])
.directive('validation', ['$q', '$timeout', 'ValidationCommon', function($q, $timeout, ValidationCommon) {
return {
restrict: "A",
require: "ngModel",
link: function(scope, elm, attrs, ctrl) {
// create an object of the common validation
var commonObj = new ValidationCommon(scope, elm, attrs, ctrl);
var _arrayErrorMessage = '';
var _promises = [];
var _timer;
var _watchers = [];
var _globalOptions = commonObj.getGlobalOptions();
// Possible element attributes
var _elmName = attrs.name;
var _validationCallback = (attrs.hasOwnProperty('validationCallback')) ? attrs.validationCallback : null;
var _validateOnEmpty = (attrs.hasOwnProperty('validateOnEmpty')) ? commonObj.parseBool(attrs.validateOnEmpty) : !!_globalOptions.validateOnEmpty;
//-- Possible validation-array attributes
// on a validation array, how many does it require to be valid?
// As soon as 'one' is valid, or does it need 'all' array values to make the input valid?
var _validArrayRequireHowMany = (attrs.hasOwnProperty('validArrayRequireHowMany')) ? attrs.validArrayRequireHowMany : "one";
var _validationArrayObjprop = (attrs.hasOwnProperty('validationArrayObjprop')) ? attrs.validationArrayObjprop : null;
// construct the functions, it's just to make the code cleaner and put the functions at bottom
var construct = {
attemptToValidate: attemptToValidate,
cancelValidation : cancelValidation
}
// create & save watcher inside an array in case we want to deregister it when removing a validator
_watchers.push({ elmName: _elmName, watcherHandler: createWatch() });
// watch the `disabled` attribute for changes
// if it become disabled then skip validation else it becomes enable then we need to revalidate it
attrs.$observe("disabled", function(disabled) {
var isDisabled = (disabled === "")
? true
: (typeof disabled === "boolean") ? disabled
: (typeof disabled !== "undefined") ? scope.$eval(disabled) : false;
if (isDisabled === true) {
// Turn off validation when element is disabled & remove it from validation summary
cancelValidation();
commonObj.removeFromValidationSummary(_elmName);
} else {
// revalidate & re-attach the onBlur event
revalidateAndAttachOnBlur();
}
});
// if DOM element gets destroyed, we need to cancel validation, unbind onBlur & remove it from $validationSummary
elm.on('$destroy', function() {
cancelAndUnbindValidation();
});
// watch for a validation attribute changing to empty, if that is the case, unbind everything from it
scope.$watch(function() {
return elm.attr('validation');
}, function(validation) {
if(typeof validation === "undefined" || validation === '') {
// if validation gets empty, we need to cancel validation, unbind onBlur & remove it from $validationSummary
cancelAndUnbindValidation();
}else {
// If validation attribute gets filled/re-filled (could be by interpolation)
// we need to redefine the validation so that we can grab the new "validation" element attribute
// and finally revalidate & re-attach the onBlur event
commonObj.defineValidation();
revalidateAndAttachOnBlur();
// if watcher not already exist, then create & save watcher inside an array in case we want to deregister it later
var foundWatcher = commonObj.arrayFindObject(_watchers, 'elmName', ctrl.$name);
if(!foundWatcher) {
_watchers.push({ elmName: _elmName, watcherHandler: createWatch() });
}
}
});
// attach the onBlur event handler on the element
elm.bind('blur', blurHandler);
// attach the angularValidation.revalidate event handler on the scope
scope.$on('angularValidation.revalidate', function(event, args){
if (args == ctrl.$name)
{
ctrl.revalidateCalled = true;
var value = ctrl.$modelValue;
var formElmObj = commonObj.getFormElementByName(ctrl.$name);
if (!!formElmObj && formElmObj.hasOwnProperty("isValidationCancelled")) {
// attempt to validate & run validation callback if user requested it
var validationPromise = attemptToValidate(value);
if(!!_validationCallback) {
commonObj.runValidationCallbackOnPromise(validationPromise, _validationCallback);
}
}
else {
ctrl.$setValidity('validation', true);
}
}
});
//----
// Private functions declaration
//----------------------------------
/** Validator function to attach to the element, this will get call whenever the input field is updated
* and is also customizable through the (typing-limit) for which inactivity this.timer will trigger validation.
* @param string value: value of the input field
* @param int typingLimit: when user stop typing, in how much time it will start validating
* @return object validation promise
*/
function attemptToValidate(value, typingLimit) {
var deferred = $q.defer();
var isValid = false;
// get the waiting delay time if passed as argument or get it from common Object
var waitingLimit = (typeof typingLimit !== "undefined") ? typingLimit : commonObj.typingLimit;
// get the form element custom object and use it after
var formElmObj = commonObj.getFormElementByName(ctrl.$name);
// if the input value is an array (like a 3rd party addons) then attempt to validate
// by exploding the array into individual input values and then validate them one value by one
if(Array.isArray(value)) {
// reset the promises array
_promises = [];
_arrayErrorMessage = '';
waitingLimit = 0;
// If we get a filled array, we will explode the array and try to validate each input value independently and
// Else when array is or become empty, we still want to validate it but without waiting time,
// a "required" validation needs to be invalid right away.
// NOTE: because most 3rd party addons support AngularJS older than 1.3, the $touched property on the element is most often not implemented
// but is required for Angular-Validation to properly display error messages and I have to force a $setTouched and by doing so force to show error message instantly on screen.
// unless someone can figure out a better approach that is universal to all addons. I could in fact also use $dirty but even that is most often not implement by adons either.
if(value.length > 0) {
// make the element as it was touched for CSS, only works in AngularJS 1.3+
if (typeof formElmObj.ctrl.$setTouched === "function") {
formElmObj.ctrl.$setTouched();
}
return explodeArrayAndAttemptToValidate(value, typeof value);
}else {
waitingLimit = 0;
}
}
// if a field holds invalid characters which are not numbers inside an `input type="number"`, then it's automatically invalid
// we will still call the `.validate()` function so that it shows also the possible other error messages
if(!!value && !!value.badInput) {
return invalidateBadInputField();
}
// pre-validate without any events just to pre-fill our validationSummary with all field errors
// passing False as the 2nd argument to hide errors from being displayed on screen
commonObj.validate(value, false);
// if field is not required and his value is empty, cancel validation and exit out
if(!commonObj.isFieldRequired() && !_validateOnEmpty && (value === "" || value === null || typeof value === "undefined")) {
cancelValidation();
deferred.resolve({ isFieldValid: true, formElmObj: formElmObj, value: value });
return deferred.promise;
}else if(!!formElmObj) {
formElmObj.isValidationCancelled = false;
}
// invalidate field before doing any validation
if((value !== "" && value !== null && typeof value !== "undefined") || commonObj.isFieldRequired() || _validateOnEmpty) {
ctrl.$setValidity('validation', false);
}
// select(options) will be validated on the spot
if(elm.prop('tagName').toUpperCase() === "SELECT") {
isValid = commonObj.validate(value, true);
ctrl.$setValidity('validation', isValid);
deferred.resolve({ isFieldValid: isValid, formElmObj: formElmObj, value: value });
return deferred.promise;
}
// onKeyDown event is the default of Angular, no need to even bind it, it will fall under here anyway
// in case the field is already pre-filled, we need to validate it without looking at the event binding
if(typeof value !== "undefined") {
// when no timer, validate right away without a $timeout. This seems quite important on the array input value check
if(typingLimit === 0) {
isValid = commonObj.validate(value, true);
scope.$evalAsync(ctrl.$setValidity('validation', isValid ));
deferred.resolve({ isFieldValid: isValid, formElmObj: formElmObj, value: value });
$timeout.cancel(_timer);
}else {
// Start validation only after the user has stopped typing in a field
// everytime a new character is typed, it will cancel/restart the timer & we'll erase any error mmsg
commonObj.updateErrorMsg('');
$timeout.cancel(_timer);
_timer = $timeout(function() {
isValid = commonObj.validate(value, true);
scope.$evalAsync(ctrl.$setValidity('validation', isValid ));
deferred.resolve({ isFieldValid: isValid, formElmObj: formElmObj, value: value });
}, waitingLimit);
}
}
return deferred.promise;
} // attemptToValidate()
/** Attempt to validate an input value that was previously exploded from the input array
* Each attempt will return a promise but only after reaching the last index, will we analyze the final validation.
* @param string: input value
* @param int: position index
* @param int: size of original array
*/
function attemptToValidateArrayInput(inputValue, index, arraySize) {
var promise = attemptToValidate(inputValue, 0);
if(!!promise && typeof promise.then === "function") {
_promises.push(promise);
// if we reached the last index
// then loop through all promises to run validation on each array input values
if(parseInt(index) === (arraySize - 1)) {
_promises.forEach(function(promise) {
promise.then(function(result) {
// user requires how many values of the array to make the form input to be valid?
// If require "one", as soon as an array value changes is valid, the complete input becomes valid
// If require "all", as soon as an array value changes is invalid, the complete input becomes invalid
switch(_validArrayRequireHowMany) {
case "all" :
if(result.isFieldValid === false) {
result.formElmObj.translatePromise.then(function(translation) {
// if user is requesting to see only the last error message, we will use '=' instead of usually concatenating with '+='
// then if validator rules has 'params' filled, then replace them inside the translation message (foo{0} {1}...), same syntax as String.format() in C#
if (_arrayErrorMessage.length > 0 && _globalOptions.displayOnlyLastErrorMsg) {
_arrayErrorMessage = '[' + result.value + '] :: ' + ((!!result.formElmObj.validator && !!result.formElmObj.validator.params) ? String.format(translation, result.formElmObj.validator.params) : translation);
} else {
_arrayErrorMessage += ' [' + result.value + '] :: ' + ((!!result.formElmObj.validator && !!result.formElmObj.validator.params) ? String.format(translation, result.formElmObj.validator.params) : translation);
}
commonObj.updateErrorMsg(_arrayErrorMessage, { isValid: false });
commonObj.addToValidationSummary(result.formElmObj, _arrayErrorMessage);
});
}
break;
case "one" :
default :
if(result.isFieldValid === true) {
ctrl.$setValidity('validation', true);
cancelValidation();
}
}
});
});
}
}
}
/** Definition of our blur event handler that will be used to attached on an element
* @param object event
*/
function blurHandler(event) {
// get the form element custom object and use it after
var formElmObj = commonObj.getFormElementByName(ctrl.$name);
var value = (typeof ctrl.$modelValue !== "undefined") ? ctrl.$modelValue : event.target.value;
if (!!formElmObj && formElmObj.hasOwnProperty("isValidationCancelled")) {
// attempt to validate & run validation callback if user requested it
var validationPromise = attemptToValidate(value, 0);
if(!!_validationCallback) {
commonObj.runValidationCallbackOnPromise(validationPromise, _validationCallback);
}
}else {
ctrl.$setValidity('validation', true);
}
}
/** Explode the input array and attempt to validate every single input values that comes out of it.
* Input array could be passed as 2 different types (array of string, array of objects)
* If we are dealing with an array of strings, we will consider the strings being the input value to validate
* But if instead it is an array of objects, we need to user to provide which object property name to use
* ex. : array of objects, var arrObj = [{ id: 1, label: 'tag1' }, { id: 2, label: 'tag2' }]
* --> we want the user to tell the directive that the input values are in the property name 'label'
* @param Array: input array
* @param string: array type
*/
function explodeArrayAndAttemptToValidate(inputArray, arrayType) {
var arraySize = inputArray.length;
// array of strings, 1 for loop to get all input values
if(arrayType === "string") {
for (var key in inputArray) {
attemptToValidateArrayInput(inputArray[key], key, arraySize);
}
}
// array of objects, 2 for loops to get all input values via an object property name defined by the user
else if(arrayType === "object") {
for (var key in inputArray) {
if (inputArray.hasOwnProperty(key)) {
var obj = inputArray[key];
for (var prop in obj) {
// check if there's a property on the object, compare it to what the user defined as the object property label
// then attempt to validate the array input value
if(obj.hasOwnProperty(prop)) {
if(!!_validationArrayObjprop && prop !== _validationArrayObjprop) {
continue;
}
attemptToValidateArrayInput(obj[prop], key, arraySize);
}
}
}
}
}
}
/** Cancel the validation, unbind onBlur and remove from $validationSummary */
function cancelAndUnbindValidation() {
// unbind everything and cancel the validation
cancelValidation();
commonObj.removeFromValidationSummary(_elmName);
// deregister the $watch from the _watchers array we kept it
var foundWatcher = commonObj.arrayFindObject(_watchers, 'elmName', ctrl.$name);
if(!!foundWatcher && typeof foundWatcher.watcherHandler === "function") {
var deregister = foundWatcher.watcherHandler(); // deregister the watch by calling his handler
_watchers.shift();
}
}
/** Cancel current validation test and blank any leftover error message */
function cancelValidation() {
// get the form element custom object and use it after
var formElmObj = commonObj.getFormElementByName(ctrl.$name);
if(!!formElmObj) {
formElmObj.isValidationCancelled = true;
}
$timeout.cancel(_timer);
commonObj.updateErrorMsg('');
ctrl.$setValidity('validation', true);
// unbind onBlur handler (if found) so that it does not fail on a non-required element that is now dirty & empty
unbindBlurHandler();
}
/** watch the element for any value change, validate it once that happen
* @return new watcher
*/
function createWatch() {
return scope.$watch(function() {
var modelValue = ctrl.$modelValue;
if(isKeyTypedBadInput()) {
return { badInput: true };
}
else if(!!_validationArrayObjprop && Array.isArray(modelValue) && modelValue.length === 0 && Object.keys(modelValue).length > 0) {
// when the modelValue is an Array but is length 0, this mean it's an Object disguise as an array
// since an Array of length 0 won't trigger a watch change, we need to return it back to an object
// for example Dropdown Multiselect when using selectionLimit of 1 will return [id: 1, label: 'John'], what we really want is the object { id: 1, label: 'John'}
// convert the object array to a real object that will go inside an array
var arr = [], obj = {};
obj[_validationArrayObjprop] = modelValue[_validationArrayObjprop]; // convert [label: 'John'] to {label: 'John'}
arr.push(obj); // push to array: [{label: 'John'}]
return arr;
}
return modelValue;
}, function(newValue, oldValue) {
if(!!newValue && !!newValue.badInput) {
unbindBlurHandler();
return invalidateBadInputField();
}
// attempt to validate & run validation callback if user requested it
var validationPromise = attemptToValidate(newValue);
if(!!_validationCallback) {
commonObj.runValidationCallbackOnPromise(validationPromise, _validationCallback);
}
}, true);
}
/** Invalidate the field that was tagged as bad input, cancel the timer validation,
* display an invalid key error and add it as well to the validation summary.
*/
function invalidateBadInputField() {
$timeout.cancel(_timer);
var formElmObj = commonObj.getFormElementByName(ctrl.$name);
commonObj.updateErrorMsg('INVALID_KEY_CHAR', { isValid: false, translate: true });
commonObj.addToValidationSummary(formElmObj, 'INVALID_KEY_CHAR', true);
}
/** Was the characters typed by the user bad input or not?
* @return bool
*/
function isKeyTypedBadInput() {
return (!!elm.prop('validity') && elm.prop('validity').badInput === true);
}
/** Re-evaluate the element and revalidate it, also re-attach the onBlur event on the element */
function revalidateAndAttachOnBlur() {
// Revalidate the input when enabled (without displaying the error)
var value = ctrl.$modelValue !== null && typeof ctrl.$modelValue !== 'undefined'
? ctrl.$modelValue
: '';
if(!Array.isArray(value)) {
ctrl.$setValidity('validation', commonObj.validate(value, false));
}
// get the form element custom object and use it after
var formElmObj = commonObj.getFormElementByName(ctrl.$name);
if(!!formElmObj) {
formElmObj.isValidationCancelled = false; // make sure validation re-enabled as well
}
// unbind previous handler (if any) not to have double handlers and then re-attach just 1 handler
unbindBlurHandler();
elm.bind('blur', blurHandler);
}
/** If found unbind the blur handler */
function unbindBlurHandler() {
if(typeof blurHandler === "function") {
elm.unbind('blur', blurHandler);
}
}
} // link()
}; // return;
}]); // directive
/**
* angular-validation-common (ghiscoding)
* https://github.com/ghiscoding/angular-validation
*
* @author: Ghislain B.
* @desc: angular-validation common functions used by both the Directive & Service
*
*/
angular
.module('ghiscoding.validation')
.factory('ValidationCommon', ['$rootScope', '$timeout', '$translate', 'ValidationRules', function ($rootScope, $timeout, $translate, ValidationRules) {
// global variables of our object (start with _var), these variables are shared between the Directive & Service
var _bFieldRequired = false; // by default we'll consider our field not required, if validation attribute calls it, then we'll start validating
var _INACTIVITY_LIMIT = 1000; // constant of maximum user inactivity time limit, this is the default cosntant but can be variable through typingLimit variable
var _formElements = []; // Array of all Form Elements, this is not a DOM Elements, these are custom objects defined as { fieldName, elm, attrs, ctrl, isValid, message }
var _globalOptions = { // Angular-Validation global options, could be define by scope.$validationOptions or by validationService.setGlobalOptions()
resetGlobalOptionsOnRouteChange: true // do we want to reset the Global Options on a route change? True by default
};
var _remotePromises = []; // keep track of promises called and running when using the Remote validator
var _validationSummary = []; // Array Validation Error Summary
var _validateOnEmpty = false; // do we want to validate on empty field? False by default
// watch on route change, then reset some global variables, so that we don't carry over other controller/view validations
$rootScope.$on("$routeChangeStart", function (event, next, current) {
resetGlobalOptions(_globalOptions.resetGlobalOptionsOnRouteChange);
});
$rootScope.$on("$stateChangeStart", function (event, next, current) {
resetGlobalOptions(_globalOptions.resetGlobalOptionsOnRouteChange);
});
// service constructor
var validationCommon = function (scope, elm, attrs, ctrl) {
this.bFieldRequired = false; // by default we'll consider our field as not required, if validation attribute calls it, then we'll start validating
this.validators = [];
this.typingLimit = _INACTIVITY_LIMIT;
this.scope = scope;
this.elm = elm;
this.ctrl = ctrl;
this.validatorAttrs = attrs;
this.validateOnEmpty = false; // do we want to always validate, even when field isn't required? False by default
this.validRequireHowMany = "all";
if(!!scope && !!scope.$validationOptions) {
_globalOptions = scope.$validationOptions; // save the global options
}
// user could pass his own scope, useful in a case of an isolate scope
if (!!scope && (!!_globalOptions.isolatedScope || !!_globalOptions.scope)) {
this.scope = _globalOptions.isolatedScope || _globalOptions.scope; // overwrite original scope (isolatedScope/scope are equivalent arguments)
_globalOptions = mergeObjects(scope.$validationOptions, _globalOptions); // reuse the validationOption from original scope
}
// if the resetGlobalOptionsOnRouteChange doesn't exist, make sure to set it to True by default
if(typeof _globalOptions.resetGlobalOptionsOnRouteChange === "undefined") {
_globalOptions.resetGlobalOptionsOnRouteChange = true;
}
// only the angular-validation Directive can possibly reach this condition with all properties filled
// on the other hand the angular-validation Service will `initialize()` function to initialize the same set of variables
if (!!this.elm && !!this.validatorAttrs && !!this.ctrl && !!this.scope) {
addToFormElementObjectList(this.elm, this.validatorAttrs, this.ctrl, this.scope);
this.defineValidation();
}
};
// list of available published public functions of this object
validationCommon.prototype.addToValidationSummary = addToValidationSummary; // add an element to the $validationSummary
validationCommon.prototype.arrayFindObject = arrayFindObject; // search an object inside an array of objects
validationCommon.prototype.arrayRemoveObject = arrayRemoveObject; // search an object inside an array of objects and remove it from array
validationCommon.prototype.defineValidation = defineValidation; // define our validation object
validationCommon.prototype.getFormElementByName = getFormElementByName; // get the form element custom object by it's name
validationCommon.prototype.getFormElements = getFormElements; // get the array of form elements (custom objects)
validationCommon.prototype.getGlobalOptions = getGlobalOptions; // get the global options used by all validators (usually called by the validationService)
validationCommon.prototype.isFieldRequired = isFieldRequired; // return boolean knowing if the current field is required
validationCommon.prototype.initialize = initialize; // initialize current object with passed arguments
validationCommon.prototype.mergeObjects = mergeObjects; // merge 2 javascript objects, Overwrites obj1's values with obj2's (basically Object2 as higher priority over Object1)
validationCommon.prototype.parseBool = parseBool; // parse a boolean value, string or bool
validationCommon.prototype.removeFromValidationSummary = removeFromValidationSummary; // remove an element from the $validationSummary
validationCommon.prototype.removeFromFormElementObjectList = removeFromFormElementObjectList; // remove named items from formElements list
validationCommon.prototype.runValidationCallbackOnPromise = runValidationCallbackOnPromise; // run a validation callback method when the promise resolve
validationCommon.prototype.setDisplayOnlyLastErrorMsg = setDisplayOnlyLastErrorMsg; // setter on the behaviour of displaying only the last error message
validationCommon.prototype.setGlobalOptions = setGlobalOptions; // set global options used by all validators (usually called by the validationService)
validationCommon.prototype.updateErrorMsg = updateErrorMsg; // update on screen an error message below current form element
validationCommon.prototype.validate = validate; // validate current element
// override some default String functions
if(window.Element && !Element.prototype.closest) {
Element.prototype.closest = elementPrototypeClosest; // Element Closest Polyfill for the browsers that don't support it (fingers point to IE)
}
String.prototype.trim = stringPrototypeTrim; // extend String object to have a trim function
String.prototype.format = stringPrototypeFormat; // extend String object to have a format function like C#
String.format = stringFormat; // extend String object to have a format function like C#
// return the service object
return validationCommon;
//----
// Public functions declaration
//----------------------------------
/** Add the error to the validation summary
* @param object self
* @param string message: error message
* @param bool need to translate: false by default
*/
function addToValidationSummary(self, message, needToTranslate) {
if (typeof self === "undefined" || self == null) {
return;
}
// get the element name, whichever we find it
var elmName = (!!self.ctrl && !!self.ctrl.$name)
? self.ctrl.$name
: (!!self.attrs && !!self.attrs.name)
? self.attrs.name
: self.elm.attr('name');
var form = getElementParentForm(elmName, self); // find the parent form (only found if it has a name)
var index = arrayFindObjectIndex(_validationSummary, 'field', elmName); // find index of object in our array
// if message is empty, remove it from the validation summary
if (index >= 0 && message === '') {
_validationSummary.splice(index, 1);
} else if (message !== '') {
if(!!needToTranslate) {
message = $translate.instant(message);
}
var friendlyName = (!!self.attrs && !!self.friendlyName) ? $translate.instant(self.friendlyName) : '';
var errorObj = { field: elmName, friendlyName: friendlyName, message: message, formName: (!!form) ? form.$name : null };
// if error already exist then refresh the error object inside the array, else push it to the array
if (index >= 0) {
_validationSummary[index] = errorObj;
} else {
_validationSummary.push(errorObj);
}
}
// save validation summary into scope root
self.scope.$validationSummary = _validationSummary;
// and also save it inside the current scope form (if found)
if (!!form) {
// since validationSummary contain errors of all forms
// we need to find only the errors of current form and them into the current scope form object
form.$validationSummary = arrayFindObjects(_validationSummary, 'formName', form.$name);
}
// also save it inside the ControllerAs alias if it was passed in the global options
if (!!_globalOptions && !!_globalOptions.controllerAs) {
_globalOptions.controllerAs.$validationSummary = _validationSummary;
// also save it inside controllerAs form (if found)
if (!!form && !!form.$name) {
var formName = form.$name.indexOf('.') >= 0 ? form.$name.split('.')[1] : form.$name;
var ctrlForm = (!!_globalOptions.controllerAs && !!_globalOptions.controllerAs[formName])
? _globalOptions.controllerAs[formName]
: ((typeof self.elm.controller() !== "undefined") ? self.elm.controller()[formName] : null);
if(!!ctrlForm) {
ctrlForm.$validationSummary = arrayFindObjects(_validationSummary, 'formName', form.$name);
}
}
}
return _validationSummary;
}
/** Define our validation object
* @return object self
*/
function defineValidation() {
var self = this;
var customUserRegEx = {};
self.validators = []; // reset the global validators
// analyze the possible element attributes
self = analyzeElementAttributes(self);
// get the rules(or validation), inside directive it's named (validation), inside service(rules)
var rules = self.validatorAttrs.rules || self.validatorAttrs.validation || '';
// We first need to see if the validation holds a custom user regex, if it does then deal with it first
// So why deal with it separately? Because a Regex might hold pipe '|' and so we don't want to mix it with our regular validation pipe
if(rules.indexOf("pattern=/") >= 0) {
var matches = rules.match(/pattern=(\/(?:(?!:alt).)*\/[igm]*)(:alt=(.*))?/);
if (!matches || matches.length < 3) {
throw 'Regex validator within the validation needs to be define with an opening "/" and a closing "/", please review your validator.';
}
var pattern = matches[1];
var altMsg = (!!matches[2]) ? matches[2].replace(/\|(.*)/, '') : '';
// convert the string into a real RegExp pattern
var match = pattern.match(new RegExp('^/(.*?)/([gimy]*)$'));
var regex = new RegExp(match[1], match[2]);
customUserRegEx = {
altMsg: altMsg,
message: altMsg.replace(/:alt=/, ''),
pattern: regex
};
// rewrite the rules so that it doesn't contain any regular expression
// we simply remove the pattern so that it won't break the Angular-Validation since it also use the pipe |
rules = rules.replace('pattern=' + pattern, 'pattern');
}
// DEPRECATED, in prior version of 1.3.34 and less, the way of writing a regular expression was through regex:/.../:regex
// this is no longer supported but is still part of the code so that it won't break for anyone using previous way of validating
// Return string will have the complete regex pattern removed but we will keep ':regex' so that we can still loop over it
else if (rules.indexOf("regex:") >= 0) {
var matches = rules.match("regex:(.*?):regex");
if (matches.length < 2) {
throw 'Regex validator within the validation needs to be define with an opening "regex:" and a closing ":regex", please review your validator.';
}
var regAttrs = matches[1].split(':=');
customUserRegEx = {
message: regAttrs[0],
pattern: regAttrs[1]
};
// rewrite the rules so that it doesn't contain the regex: ... :regex ending
// we simply remove it so that it won't break if there's a pipe | inside the actual regex
rules = rules.replace(matches[0], 'regex:');
}
// at this point it's safe to split with pipe (since regex was previously stripped out)
var validations = rules.split('|');
if (validations) {
self.bFieldRequired = (rules.indexOf("required") >= 0);
// loop through all validators of the element
for (var i = 0, ln = validations.length; i < ln; i++) {
// check if user provided an alternate text to his validator (validator:alt=Alternate Text)
var posAltText = validations[i].indexOf("alt=");
var hasAltText = posAltText >= 0;
var params = [];
// alternate text might have the character ":" inside it, so we need to compensate
// since altText is always at the end, we can before the altText and add back this untouched altText to our params array
if(hasAltText) {
params = validations[i].substring(0,posAltText-1).split(':'); // split before altText, so we won't touch it
params.push(validations[i].substring(posAltText)); // add back the altText to our split params array
}else {
// params split will be:: [0]=rule, [1]=ruleExtraParams OR altText, [2] altText
params = validations[i].split(':');
}
self.validators[i] = ValidationRules.getElementValidators({
altText: hasAltText === true ? (params.length === 2 ? params[1] : params[2]) : '',
customRegEx: customUserRegEx,
rule: params[0],
ruleParams: (hasAltText && params.length === 2) ? null : params[1]
});
}
}
return self;
} // defineValidation()
/** Return a Form element object by it's name
* @param string element input name
* @return array object elements
*/
function getFormElementByName(elmName) {
return arrayFindObject(_formElements, 'fieldName', elmName);
}
/** Return all Form elements
* @param string form name
* @return array object elements
*/
function getFormElements(formName) {
if(!!formName) {
return arrayFindObjects(_formElements, 'formName', formName);
}
return _formElements;
}
/** Get global options used by all validators
* @return object global options
*/
function getGlobalOptions() {
return _globalOptions;
}
/** Initialize the common object
* @param object scope
* @param object elm
* @param object attrs
* @param object ctrl
*/
function initialize(scope, elm, attrs, ctrl) {
this.scope = scope;
this.elm = elm;
this.ctrl = ctrl;
this.validatorAttrs = attrs;
addToFormElementObjectList(elm, attrs, ctrl, scope);
this.defineValidation();
}
/** @return isFieldRequired */
function isFieldRequired() {
var self = this;
return self.bFieldRequired;
}
/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* When both object have the same property, the Object2 will higher priority over Object1 (basically that property will be overwritten inside Object1)
* @param obj1
* @param obj2
* @return obj3 a new object based on obj1 and obj2
*/
function mergeObjects(obj1, obj2) {
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}
/** Remove objects from FormElement list.
* @param element input name to remove
*/
function removeFromFormElementObjectList(elmName) {
var index = arrayFindObjectIndex(_formElements, 'fieldName', elmName); // find index of object in our array
if (index >= 0) {
_formElements.splice(index, 1);
}
}
/** Remove an element from the $validationSummary array
* @param string elmName: element name
* @param object validationSummary
*/
function removeFromValidationSummary(elmName, validationSummaryObj) {
var self = this;
var form = getElementParentForm(elmName, self); // find the parent form (only found if it has a name)
var vsObj = validationSummaryObj || _validationSummary;
var index = arrayFindObjectIndex(vsObj, 'field', elmName); // find index of object in our array
// if message is empty, remove it from the validation summary object
if (index >= 0) {
vsObj.splice(index, 1);
}
// also remove from 'local' validationSummary
index = arrayFindObjectIndex(_validationSummary, 'field', elmName); // find index of object in our array
if (index >= 0) {
_validationSummary.splice(index, 1);
}
self.scope.$validationSummary = _validationSummary;
// overwrite the scope form (if found)
if (!!form) {
// since validationSummary contain errors of all forms
// we need to find only the errors of current form and them into the current scope form object
form.$validationSummary = arrayFindObjects(_validationSummary, 'formName', form.$name);
}
// overwrite the ControllerAs alias if it was passed in the global options
if (!!_globalOptions && !!_globalOptions.controllerAs) {
_globalOptions.controllerAs.$validationSummary = _validationSummary;
// also overwrite it inside controllerAs form (if found)
if (!!form) {
var formName = form.$name.indexOf('.') >= 0 ? form.$name.split('.')[1] : form.$name;
if(!!_globalOptions.controllerAs[formName]) {
_globalOptions.controllerAs[formName].$validationSummary = arrayFindObjects(_validationSummary, 'formName', form.$name);
}
}
}
return _validationSummary;
}
/** Evaluate a function name passed as string and run it from the scope.
* The function name could be passed with/without brackets "()", in any case we will run the function
* @param object self object
* @param string function passed as a string
* @param mixed result
*/
function runEvalScopeFunction(self, fnString) {
var result;
// Find if our function has the brackets "()"
// if yes then run it through $eval else find it in the scope and then run it
if(/\({1}.*\){1}/gi.test(fnString)) {
result = self.scope.$eval(fnString);
}else {
var fct = objectFindById(self.scope, fnString, '.');
if(typeof fct === "function") {
result = fct();
}
}
return result;
}
/** Run a validation callback function once the promise return
* @param object validation promise
* @param string callback function name (could be with/without the brackets () )
*/
function runValidationCallbackOnPromise(promise, callbackFct) {
var self = this;
if(typeof promise.then === "function") {
promise.then(function() {
runEvalScopeFunction(self, callbackFct);
});
}
}
/** Setter on the behaviour of displaying only the last error message of each element.
* By default this is false, so the behavior is to display all error messages of each element.
* @param boolean value
*/
function setDisplayOnlyLastErrorMsg(boolValue) {
_globalOptions.displayOnlyLastErrorMsg = boolValue;
}
/** Set and initialize global options used by all validators
* @param object attrs: global options
* @return object self
*/
function setGlobalOptions(options) {
var self = this;
// merge both attributes but 2nd object (attrs) as higher priority, so that for example debounce property inside `attrs` as higher priority over `validatorAttrs`
// so the position inside the mergeObject call is very important
_globalOptions = mergeObjects(_globalOptions, options); // save in global
return self;
}
/** in general we will display error message at the next element after our input as <span class="validation validation-inputName text-danger">
* but in some cases user might want to define which DOM id to display error (as validation attribute)
* @param string message: error message to display
* @param object arguments that could be passed to the function
*/
function updateErrorMsg(message, attrs) {
var self = this;
// attrs.obj if set, should be a commonObj, and can be self.
// In addition we need to set validatorAttrs, as they are defined as attrs on obj.
if (!!attrs && attrs.obj) {
self = attrs.obj;
self.validatorAttrs = attrs.obj.attrs;
}
// element name could be defined in the `attrs` or in the self object
var elm = (!!attrs && attrs.elm) ? attrs.elm : self.elm;
var elmName = (!!elm && elm.attr('name')) ? elm.attr('name') : null;
// Make sure that element has a name="" attribute else it will not work
if (typeof elmName === "undefined" || elmName === null) {
var ngModelName = (!!elm) ? elm.attr('ng-model') : 'unknown';
throw 'Angular-Validation Service requires you to have a (name="") attribute on the element to validate... Your element is: ng-model="' + ngModelName + '"';
}
// user might have passed a message to be translated
var errorMsg = (!!attrs && !!attrs.translate) ? $translate.instant(message) : message;
errorMsg = errorMsg.trim();
// get the name attribute of current element, make sure to strip dirty characters, for example remove a <input name="options[]"/>, we need to strip the "[]"
// also replace any possible '.' inside the input name by '-'
var elmInputName = elmName.replace(/[|&;$%@"<>()+,\[\]\{\}]/g, '').replace(/\./g, '-');
var errorElm = null;
// find the element which we'll display the error message, this element might be defined by the user with 'validationErrorTo'
if (!!self.validatorAttrs && self.validatorAttrs.hasOwnProperty('validationErrorTo')) {
// validationErrorTo can be used in 3 different ways: with '.' (element error className) or with/without '#' (element error id)
var firstChar = self.validatorAttrs.validationErrorTo.charAt(0);
var selector = (firstChar === '.' || firstChar === '#') ? self.validatorAttrs.validationErrorTo : '#' + self.validatorAttrs.validationErrorTo;
errorElm = angular.element(document.querySelector(selector));
}
// errorElm can be empty due to:
// 1. validationErrorTo has not been set
// 2. validationErrorTo has been mistyped, and if mistyped, use regular functionality
if (!errorElm || errorElm.length === 0) {
// most common way, let's try to find our <span class="validation-inputName">
errorElm = angular.element(document.querySelector('.validation-' + elmInputName));
}
// form might have already been submitted
var isSubmitted = (!!attrs && attrs.isSubmitted) ? attrs.isSubmitted : false;
// invalid & isDirty, display the error message... if <span> not exist then create it, else udpate the <span> text
if (!_globalOptions.hideErrorUnderInputs && !!attrs && !attrs.isValid && (isSubmitted || self.ctrl.$dirty || self.ctrl.$touched || self.ctrl.revalidateCalled)) {
(errorElm.length > 0) ? errorElm.html(errorMsg) : elm.after('<div class="validation validation-' + elmInputName + ' text-danger">' + errorMsg + '</div>');
self.ctrl.isErrorMessageVisible = true;
} else {
errorElm.html(''); // element is pristine or no validation applied, error message has to be blank
self.ctrl.isErrorMessageVisible = undefined;
}
}
/** Validate function, from the input value it will go through all validators (separated by pipe)
* that were passed to the input element and will validate it. If field is invalid it will update
* the error text of the span/div element dedicated for that error display.
* @param string value: value of the input field
* @param bool showError: do we want to show the error or hide it (false is useful for adding error to $validationSummary without displaying it on screen)
* @return bool isFieldValid
*/
function validate(strValue, showError) {
var self = this;
var isConditionValid = true;
var isFieldValid = true;
var nbValid = 0;
var validator;
var validatedObject = {};
// make an object to hold the message so that we can reuse the object by reference
// in some of the validation check (for example "matching" and "remote")
var validationElmObj = {
message: ''
}
// to make proper validation, our element value cannot be an undefined variable (we will at minimum make it an empty string)
// For example, in some particular cases "undefined" returns always True on regex.test() which is incorrect especially on max_len:x
if (typeof strValue === "undefined") {
strValue = '';
}
// get some common variables
var elmName = (!!self.ctrl && !!self.ctrl.$name)
? self.ctrl.$name
: (!!self.attrs && !!self.attrs.name)
? self.attrs.name
: self.elm.attr('name');
var formElmObj = getFormElementByName(elmName);
var rules = self.validatorAttrs.rules || self.validatorAttrs.validation;
// loop through all validators (could be multiple)
for (var j = 0, jln = self.validators.length; j < jln; j++) {
validator = self.validators[j];
// When AutoDetect it will auto-detect the type and rewrite the conditions or regex pattern, depending on type found
if (validator.type === "autoDetect") {
validator = validatorAutoDetectType(validator, strValue);
}
// get the disabled & ngDisabled attributes if found
var elmAttrDisabled = self.elm.prop("disabled");
var elmAttrNgDisabled = (!!self.attrs) ? self.attrs.ngDisabled : self.validatorAttrs.ngDisabled;
var isDisabled = (elmAttrDisabled === "")
? true
: (typeof elmAttrDisabled === "boolean")
? elmAttrDisabled
: (typeof elmAttrDisabled !== "undefined") ? self.scope.$eval(elmAttrDisabled) : false;
var isNgDisabled = (elmAttrNgDisabled === "")
? true
: (typeof elmAttrNgDisabled === "boolean")
? elmAttrNgDisabled
: (typeof elmAttrNgDisabled !== "undefined") ? self.scope.$eval(elmAttrNgDisabled) : false;