Advanced form validation with AngularJS and filters
PDFHere’s a neat little trick I discovered that let’s you do wildcard expression checks for an input value:
The form
in this example ensures that registered persons must be unique by their name:
1 |
And the directive that makes this possible:
1 2 3 4 5 6 7 8 9 10 11 | app.directive('ensureExpression', ['$http', '$parse', function($http, $parse) { return { require: 'ng-model', link: function(scope, ele, attrs, ngModelController) { scope.$watch(attrs.ngModel, function(value) { var booleanResult = $parse(attrs.ensureExpression)(scope); ngModelController.$setValidity('expression', booleanResult); }); } }; }]); |
It’s similar to ui-validate, but you don’t need a scope specific validation function (this works generically) and ofcourse you don’t need angular-ui-utils this way.
In fact, it’s easy to add support for custom validation names and multiple expressions:
1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | app.directive('ensureExpression', ['$parse', function($parse) { return { require: 'ng-model', link: function(scope, ele, attrs, ngModelController) { scope.$watch(attrs.ngModel, function(value) { var expressionResults = $parse(attrs.ensureExpression)(scope); for (var expressionName in expressionResults) { ngModelController.$setValidity(expressionName, expressionResults[expressionName]); } }); } }; }]); |