Can I programmatically apply Angular validation directives inside a custom directive?

后端 未结 5 1425
[愿得一人]
[愿得一人] 2020-12-29 20:05

I have found great many occurrences of the following pattern for html inputs, this being for phone numbers:



        
5条回答
  •  抹茶落季
    2020-12-29 20:39

    If you're using more validations, you can create a service that is responsible for identifying and validating the elements, without any limitation. Default directives of angular remain.

    Example:

        module.service('$Validation', ["$compile",function($compile){
    
            this.validators = {
                'phoneNumber': [['required', 1], ['minlength',6], ['maxlength', 10], ['pattern', /^[0-9]+$/.source]],
                'phoneNumber2Custom': function(value){ 
                    return /^[0-9]{6,10}$/.test(value) 
                },
                'userTwitter': function(value){
                    return /^@(.+)/.test(value)
                }
                // ...etc... /
            }
    
            this.add = function(scope, element, attrs, model){
                var name = attrs.bkNgValidation, type;
                if(!(type = this.validators[name])) return;
                else if(angular.isFunction(type)) return (model.$validators[name] = type);
    
                element.removeAttr("bk-ng-validation");
                angular.forEach(type, function(expr){
                    element.attr(expr[0], expr[1])
                });
                $compile(element)(scope)        
            };
    
        }]).directive('bkNgValidation', ["$Validation", function ($Validation) {
            return {
                require: '?ngModel',
                priority: 1e5,
                link: function(){
                    $Validation.add.apply($Validation, arguments);
                }
            }
        }])
    

    Demo

提交回复
热议问题