forked from dsjoerg/ggtracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.js
More file actions
48 lines (44 loc) · 1.86 KB
/
Copy pathvalidate.js
File metadata and controls
48 lines (44 loc) · 1.86 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
/**
* General-purpose validator for ngModel.
* angular.js comes with several built-in validation mechanism for input fields (ngRequired, ngPattern etc.) but using
* an arbitrary validation function requires creation of a custom formatters and / or parsers.
* The ui-validate directive makes it easy to use any function(s) defined in scope as a validator function(s).
* A validator function will trigger validation on both model and input changes.
*
* @example <input ui-validate="myValidatorFunction">
* @example <input ui-validate="{foo : validateFoo, bar : validateBar}">
*
* @param ui-validate {string|object literal} If strings is passed it should be a scope's function to be used as a validator.
* If an object literal is passed a key denotes a validation error key while a value should be a validator function.
* In both cases validator function should take a value to validate as its argument and should return true/false indicating a validation result.
*/
angular.module('ui.directives').directive('uiValidate', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var validateFn, validateExpr = attrs.uiValidate;
validateExpr = scope.$eval(validateExpr);
if (!validateExpr) {
console.log('WHASd');
return;
}
if (angular.isFunction(validateExpr)) {
validateExpr = { validator: validateExpr };
}
angular.forEach(validateExpr, function (validatorFn, key) {
validateFn = function (valueToValidate) {
if (validatorFn(valueToValidate)) {
ctrl.$setValidity(key, true);
return valueToValidate;
} else {
ctrl.$setValidity(key, false);
return undefined;
}
};
ctrl.$formatters.push(validateFn);
ctrl.$parsers.push(validateFn);
});
}
};
});