-
Notifications
You must be signed in to change notification settings - Fork 176
/
validator.directive.js
484 lines (429 loc) · 16.2 KB
/
validator.directive.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
(function() {
angular
.module('validation.directive')
.directive('validator', Validator);
function Validator($injector) {
var $validationProvider = $injector.get('$validation');
var $q = $injector.get('$q');
var $timeout = $injector.get('$timeout');
var $compile = $injector.get('$compile');
var $parse = $injector.get('$parse');
var groups = {};
/**
* Do this function if validation valid
* @param element
* @param validMessage
* @param validation
* @param callback
* @param ctrl
* @returns {}
*/
var validFunc = function(element, validMessage, validation, scope, ctrl, attrs, param) {
var messageToShow = validMessage || $validationProvider.getDefaultMsg(validation).success;
var validCallback = $parse(attrs.validCallback);
var messageId = attrs.messageId;
var validationGroup = attrs.validationGroup;
var messageElem;
if (messageId || validationGroup) messageElem = angular.element(document.querySelector('#' + (messageId || validationGroup)));
else messageElem = $validationProvider.getMsgElement(element);
if (element.attr('no-validation-message')) {
messageElem.css('display', 'none');
} else if ($validationProvider.showSuccessMessage && messageToShow) {
messageToShow = angular.isFunction(messageToShow) ? messageToShow(element, attrs, param) : messageToShow;
messageElem.html('').append($compile($validationProvider.getSuccessHTML(messageToShow, element, attrs))(scope));
messageElem.css('display', '');
} else {
messageElem.css('display', 'none');
}
ctrl.$setValidity(ctrl.$name, true);
validCallback(scope, {
message: messageToShow
});
if ($validationProvider.validCallback) $validationProvider.validCallback(element);
return true;
};
/**
* Do this function if validation invalid
* @param element
* @param validMessage
* @param validation
* @param callback
* @param ctrl
* @returns {}
*/
var invalidFunc = function(element, validMessage, validation, scope, ctrl, attrs, param) {
var messageToShow = validMessage || $validationProvider.getDefaultMsg(validation).error;
var invalidCallback = $parse(attrs.invalidCallback);
var messageId = attrs.messageId;
var validationGroup = attrs.validationGroup;
var messageElem;
if (messageId || validationGroup) messageElem = angular.element(document.querySelector('#' + (messageId || validationGroup)));
else messageElem = $validationProvider.getMsgElement(element);
if (element.attr('no-validation-message')) {
messageElem.css('display', 'none');
} else if ($validationProvider.showErrorMessage && messageToShow) {
messageToShow = angular.isFunction(messageToShow) ? messageToShow(element, attrs, param) : messageToShow;
messageElem.html('').append($compile($validationProvider.getErrorHTML(messageToShow, element, attrs))(scope));
messageElem.css('display', '');
} else {
messageElem.css('display', 'none');
}
ctrl.$setValidity(ctrl.$name, false);
invalidCallback(scope, {
message: messageToShow
});
if ($validationProvider.invalidCallback) $validationProvider.invalidCallback(element);
return false;
};
/**
* Verify whether there is one of the elements inside the group valid.
* If so, it returns true, otherwise, it returns false
*
* @param validationGroup
* @return {boolean}
*/
var checkValidationGroup = function(validationGroup) {
var group = groups[validationGroup];
return Object.keys(group).some(function(key) {
return group[key];
});
};
/**
* Set validity to all elements inside the given group
*
* @param scope
* @param groupName
* @param validity
*/
function setValidationGroup(scope, validationGroup, validity) {
var validationGroupElems = document.querySelectorAll('*[validation-group=' + validationGroup + ']');
// Loop through all elements inside the group
for (var i = 0, len = validationGroupElems.length; i < len; i++) {
var elem = validationGroupElems[i];
var formName = elem.form.name;
var elemName = elem.name;
scope[formName][elemName].$setValidity(elemName, validity);
}
}
/**
* collect elements for focus
* @type {Object}
***private variable
*/
var focusElements = {};
/**
* Get Validation Result Object
* @param data
* @returns {
* result: Boolean, // is success or error
* message: String // tips
* }
*/
function getResultObj(data) {
var res = {};
if (data && data.length > 0) {
res = data[0];
if (!angular.isObject(res)) {
res = {
result: res,
message: ''
};
}
} else {
res = {
result: false,
message: ''
};
}
return res;
}
/**
* Check Validation with Function or RegExp
* @param scope
* @param element
* @param attrs
* @param ctrl
* @param validation
* @param value
* @returns {}
*/
var checkValidation = function(scope, element, attrs, ctrl, validation, value) {
var validators = validation.slice(0);
var validatorExpr = validators[0].trim();
var paramIndex = validatorExpr.indexOf('=');
var validator = paramIndex === -1 ? validatorExpr : validatorExpr.substr(0, paramIndex);
var validatorParam = paramIndex === -1 ? null : validatorExpr.substr(paramIndex + 1);
var leftValidation = validators.slice(1);
var successMessage = validator + 'SuccessMessage';
var errorMessage = validator + 'ErrorMessage';
var expression = $validationProvider.getExpression(validator);
var validationGroup = attrs.validationGroup;
var valid = {
success: function(message) {
validFunc(element, message || attrs[successMessage], validator, scope, ctrl, attrs, validatorParam);
if (leftValidation.length) {
return checkValidation(scope, element, attrs, ctrl, leftValidation, value);
} else {
return true;
}
},
error: function(message) {
return invalidFunc(element, message || attrs[errorMessage], validator, scope, ctrl, attrs, validatorParam);
}
};
if (expression === undefined) {
console.error('You are using undefined validator "%s"', validator);
if (leftValidation.length) return checkValidation(scope, element, attrs, ctrl, leftValidation, value);
else return;
}
// Check with Function
if (expression.constructor === Function) {
return $q.all([$validationProvider.getExpression(validator)(value, scope, element, attrs, validatorParam)])
.then(function(data) {
var resultObj = getResultObj(data);
var message = resultObj.message;
if (resultObj.result) {
if (validationGroup) {
groups[validationGroup][ctrl.$name] = true;
setValidationGroup(scope, validationGroup, true);
}
return valid.success(message);
} else if (validationGroup) {
groups[validationGroup][ctrl.$name] = false;
// Whenever the element is invalid, we'll check whether one of the elements inside the its group valid or not.
// If there is a valid element, its invalid message won't be shown, Otherwise, shows its invalid message.
if (checkValidationGroup(validationGroup)) {
setValidationGroup(scope, validationGroup, true);
} else {
setValidationGroup(scope, validationGroup, false);
return valid.error(message);
}
} else return valid.error(message);
}, function() {
return valid.error();
});
}
// Check with RegExp
else if (expression.constructor === RegExp) {
// Only apply the test if the value is neither undefined or null
if (value !== undefined && value !== null) {
if ($validationProvider.getExpression(validator).test(value)) {
if (validationGroup) {
groups[validationGroup][ctrl.$name] = true;
setValidationGroup(scope, validationGroup, true);
}
return valid.success();
} else if (validationGroup) {
groups[validationGroup][ctrl.$name] = false;
// Whenever the element is invalid, we'll check whether one of the elements inside the its group valid or not.
// If there is a valid element, its invalid message won't be shown, Otherwise, shows its invalid message.
if (checkValidationGroup(validationGroup)) {
setValidationGroup(scope, validationGroup, true);
} else {
setValidationGroup(scope, validationGroup, false);
return valid.error();
}
} else return valid.error();
}
} else return valid.error();
};
/**
* generate unique guid
*/
var s4 = function() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
var guid = function() {
return (s4() + s4() + s4() + s4());
};
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
/**
* All attributes
*/
var useViewValue = attrs.useViewValue !== 'false';
var validator = attrs.validator;
var messageId = attrs.messageId;
var validationGroup = attrs.validationGroup;
var validMethod = attrs.validMethod;
var ngModel = attrs.ngModel;
/**
* watch
* @type {watch}
*
* Use to collect scope.$watch method
*
* use watch() to destroy the $watch method
*/
var watch = function() {};
/**
* validator
* @type {Array}
*
* Convert user input String to Array
*/
var validation = validator.split(',');
/**
* guid use
*/
var uid = ctrl.validationId = guid();
/**
* to have a value to rollback to
*/
var originalViewValue = null;
/**
* Set initial validity to undefined if no boolean value is transmitted
*/
var initialValidity = void 0;
if (typeof attrs.initialValidity === 'boolean') {
initialValidity = attrs.initialValidity;
}
/**
* Observe validator changes in order to allow dynamically change it
*/
attrs.$observe('validator', function(value) {
validation = value.split(',');
});
/**
* Set up groups object in order to keep track validation of elements
*/
if (validationGroup) {
if (!groups[validationGroup]) groups[validationGroup] = {};
groups[validationGroup][ctrl.$name] = false;
}
/**
* Default Valid/Invalid Message
*/
if (!(messageId || validationGroup)) $validationProvider.addMsgElement(element);
/**
* Set custom initial validity
* Usage: <input initial-validity="true" ... >
*/
ctrl.$setValidity(ctrl.$name, initialValidity);
/**
* Reset the validation for specific form
*/
scope.$on(ctrl.$name + 'reset-' + uid, function() {
/**
* clear scope.$watch here
* when reset status
* clear the $watch method to prevent
* $watch again while reset the form
*/
watch();
$timeout(function() {
ctrl.$setViewValue(originalViewValue);
ctrl.$setPristine();
ctrl.$setValidity(ctrl.$name, undefined);
ctrl.$render();
if (messageId || validationGroup) angular.element(document.querySelector('#' + (messageId || validationGroup))).html('');
else $validationProvider.getMsgElement(element).html('');
if ($validationProvider.resetCallback) $validationProvider.resetCallback(element);
});
});
/**
* Check validator
*/
validMethod = (angular.isUndefined(validMethod)) ? $validationProvider.getValidMethod() : validMethod;
/**
* Click submit form, check the validity when submit
*/
scope.$on(ctrl.$name + 'submit-' + uid, function(event, index) {
var value = useViewValue ? ctrl.$viewValue : ctrl.$modelValue;
var isValid = false;
isValid = checkValidation(scope, element, attrs, ctrl, validation, value);
if (validMethod === 'submit') {
// clear previous scope.$watch
watch();
watch = scope.$watch(function() {
return scope.$eval(ngModel);
}, function(value, oldValue) {
// don't watch when init
if (value === oldValue) {
return;
}
// scope.$watch will translate '' to undefined
// undefined/null will pass the required submit /^.+/
// cause some error in this validation
if (value === undefined || value === null) {
value = '';
}
isValid = checkValidation(scope, element, attrs, ctrl, validation, value);
});
}
var setFocus = function(isValid) {
if (isValid) {
delete focusElements[index];
} else {
focusElements[index] = element[0];
$timeout(function() {
focusElements[Math.min.apply(null, Object.keys(focusElements))].focus();
}, 0);
}
};
if (isValid instanceof Object) isValid.then(setFocus);
else setFocus(isValid);
});
/**
* Validate blur method
*/
if (validMethod === 'blur') {
element.bind('blur', function() {
var value = scope.$eval(ngModel);
if (scope.$root.$$phase !== '$apply') {
scope.$apply(function() {
checkValidation(scope, element, attrs, ctrl, validation, value);
});
} else {
checkValidation(scope, element, attrs, ctrl, validation, value);
}
});
return;
}
/**
* Validate submit & submit-only method
*/
if (validMethod === 'submit' || validMethod === 'submit-only') {
return;
}
/**
* Validate watch method
* This is the default method
*/
scope.$watch(function() {
return scope.$eval(ngModel);
}, function(value) {
/**
* dirty, pristine, viewValue control here
*/
if (ctrl.$pristine && ctrl.$viewValue) {
// has value when initial
originalViewValue = ctrl.$viewValue || '';
ctrl.$setViewValue(ctrl.$viewValue);
} else if (ctrl.$pristine) {
// Don't validate form when the input is clean(pristine)
if (messageId || validationGroup) angular.element(document.querySelector('#' + (messageId || validationGroup))).html('');
else $validationProvider.getMsgElement(element).html('');
return;
}
checkValidation(scope, element, attrs, ctrl, validation, value);
});
$timeout(function() {
/**
* Don't showup the validation Message
*/
attrs.$observe('noValidationMessage', function(value) {
var el;
if (messageId || validationGroup) el = angular.element(document.querySelector('#' + (messageId || validationGroup)));
else el = $validationProvider.getMsgElement(element);
if (value === 'true' || value === true) el.css('display', 'none');
else if (value === 'false' || value === false) el.css('display', 'block');
});
});
}
};
}
Validator.$inject = ['$injector'];
}).call(this);