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
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.