Form validation - Required one of many in a group

后端 未结 8 1209
时光取名叫无心
时光取名叫无心 2020-12-05 18:31

In the project I\'m working on at the moment I currently have three textboxes and I need to validate that at least one of the text boxes has been populated.

I\'ve be

8条回答
  •  醉梦人生
    2020-12-05 19:36

    I had similar grouping requirement in my project and I wrote this.Interested people can use this

    .directive('group',function(){
            return {
                require: '^form',
                link : function($scope,element,attrs,formCtrl){
                    var ctrls =[];
    
                    element.find(".group-member").each(function(){
                        var member = angular.element($(this));
                        var mdlCtrl = member.data("$ngModelController");
                        if(!mdlCtrl){
                            throw "Group member should have ng-model";
                        }
                        ctrls.push(mdlCtrl);
                    });
    
                    var errKey = attrs['name']+"GrpReqd";
                    var min = attrs['minRequired'] || 1;
                    var max = attrs['maxRequired'] || ctrls.length;
    
                    $scope.validateGroup = function(){
                        var defined=0;
                        for(i=0;i max){
                            formCtrl.$setValidity(errKey,false);
                        } else {
                            formCtrl.$setValidity(errKey,true);
                        }
                    };
    
                    //support real time validation
                    angular.forEach(ctrls,function(mdlCtrl){
                        $scope.$watch(function () {
                              return mdlCtrl.$modelValue;
                           }, $scope.validateGroup);
                    });
    
                }
            };
        })
    

    HTML usage :

    Here group directive identifies the logical grouping. This directive sits on an element without ng-model, a div in the above example. group directive receives 2 optional attribute min-required and max-required. Group members are identified using group-member class on individual fields. Group members are supposed to have an ng-model for binding. Since group directive doesn't have an ng-model error will be emitted under yourForm.$error.CancellationInfoGrpReqd in the above case. Unique Error key is generated from the element name on which group directive is sitting with GrpReqd appended to it.

提交回复
热议问题