How to add custom validation to an AngularJS form?

后端 未结 12 1695
既然无缘
既然无缘 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:45

    I recently created a directive to allow for expression-based invalidation of angular form inputs. Any valid angular expression can be used, and it supports custom validation keys using object notation. Tested with angular v1.3.8

            .directive('invalidIf', [function () {
            return {
                require: 'ngModel',
                link: function (scope, elm, attrs, ctrl) {
    
                    var argsObject = scope.$eval(attrs.invalidIf);
    
                    if (!angular.isObject(argsObject)) {
                        argsObject = { invalidIf: attrs.invalidIf };
                    }
    
                    for (var validationKey in argsObject) {
                        scope.$watch(argsObject[validationKey], function (newVal) {
                            ctrl.$setValidity(validationKey, !newVal);
                        });
                    }
                }
            };
        }]);
    

    You can use it like this:

    
    
    
    
    

提交回复
热议问题