How to add custom validation to an AngularJS form?

后端 未结 12 1621
既然无缘
既然无缘 2020-11-22 10:07

I have a form with input fields and validation setup by adding the required attributes and such. But for some fields I need to do some extra validation. How wou

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 10:40

    Here's a cool way to do custom wildcard expression validations in a form (from: Advanced form validation with AngularJS and filters):

    app.directive('ensureExpression', ['$http', '$parse', function($http, $parse) {
        return {
            require: 'ngModel',
            link: function(scope, ele, attrs, ngModelController) {
                scope.$watch(attrs.ngModel, function(value) {
                    var booleanResult = $parse(attrs.ensureExpression)(scope);
                    ngModelController.$setValidity('expression', booleanResult);
                });
            }
        };
    }]);
    

    jsFiddle demo (supports expression naming and multiple expressions)

    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 ui.utils this way.

提交回复
热议问题