Permalink
Browse files

Rewrote ui-validate to have support for ui-validate-watch

The tests have not been updated yet to reflect the new syntax
  • Loading branch information...
1 parent 8d9aca8 commit 0fd2b9c6eb7b4fd2a6cf06918c35ab5ae3b2a3bb Dean Sofer committed Sep 12, 2012
Showing with 28 additions and 9 deletions.
  1. +28 −9 modules/directives/validate/validate.js
@@ -5,8 +5,10 @@
* 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}">
+ * @example <input ui-validate=" 'myValidatorFunction($value)' ">
+ * @example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }">
+ * @example <input ui-validate="{ foo : '$value > anotherModel' }" ui-validate-watch=" 'anotherModel' ">
+ * @example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }" ui-validate-watch=" { foo : 'anotherModel' } ">
*
* @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.
@@ -19,30 +21,47 @@ angular.module('ui.directives').directive('uiValidate', function () {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
- var validateFn, validateExpr = attrs.uiValidate;
+ var validateFn, watch, validators = {},
+ validateExpr = scope.$eval(attrs.uiValidate);
- validateExpr = scope.$eval(validateExpr);
- if (!validateExpr) {
- return;
- }
+ if (!validateExpr) return;
- if (angular.isFunction(validateExpr)) {
+ if (angular.isString(validateExpr)) {
validateExpr = { validator: validateExpr };
}
angular.forEach(validateExpr, function (validatorFn, key) {
validateFn = function (valueToValidate) {
- if (validatorFn(valueToValidate)) {
+ if (scope.$eval(validatorFn, { '$value' : valueToValidate })) {
ctrl.$setValidity(key, true);
return valueToValidate;
} else {
ctrl.$setValidity(key, false);
return undefined;
}
};
+ validators[key] = validateFn;
ctrl.$formatters.push(validateFn);
ctrl.$parsers.push(validateFn);
});
+
+ // Support for ui-validate-watch
+ if (attrs.uiValidateWatch) {
+ watch = scope.$eval(attrs.uiValidateWatch);
+ if (angular.isString(watch)) {
+ scope.$watch(watch, function(){
+ angular.forEach(validators, function(validatorFn, key){
+ validatorFn(ctrl.$viewValue);
+ });
+ });
+ } else {
+ angular.forEach(watch, function(expression, key){
+ scope.$watch(expression, function(){
+ validatorFn[key](ctrl.$viewValue);
+ });
+ });
+ }
+ }
}
};
});

0 comments on commit 0fd2b9c

Please sign in to comment.