如何使用angular来实现复选框组所需的验证?

时间:2021-02-02 22:49:44

I have html template with the checkbox input in it, and at least one of them is selected in the group to pass the required validation.

我有html模板,其中包含复选框输入,并且在组中至少选择了其中一个模板以传递所需的验证。

HTML:

<input class="cb" type="checkbox" value="1" ng-model="form.cb.one"
        ng-required="showRequired" ng-change="handleClick()">one</input>
<input class="cb" type="checkbox" value="2" ng-model="form.cb.two"
       ng-required="showRequired" ng-change="handleClick()">two</input>...

JS:

$scope.showRequired=true;
$scope.form.cb = {one:false, two:true, three:false}
$scope.handleChange = function(){
$scope.showRequired = !($scope.chkCollection.one || $scope.chkCollection.two || $scope.chkCollection.three);
};

I was planning to change the ng-required attribute for the validation on click of the checkbox, but since it is a template, it may have the same variable name($scope.showRequired) used in other places on the page, which could affect other required fields. How to solve this problem? Thanks

我打算在点击复选框时更改验证的ng-required属性,但由于它是一个模板,它可能在页面上的其他位置使用相同的变量名称($ scope.showRequired),这可能会影响其他必填字段。如何解决这个问题呢?谢谢

1 个解决方案

#1


0  

Does one of the form.cb group need to be checked? If you need to do more validation, you could do this after your showRequired line, which takes into account showRequired:

是否需要检查form.cb组之一?如果您需要进行更多验证,可以在showRequired行之后执行此操作,该行考虑了showRequired:

<input class="cb" type="checkbox" value="1" ng-model="form.cb.one"
    ng-required="showRequiredCheckbox()" ng-change="handleClick()">one</input>
<input class="cb" type="checkbox" value="2" ng-model="form.cb.two"
   ng-required="showRequiredCheckbox()" ng-change="handleClick()">two</input>...

And js:

$scope.showRequired = !($scope.chkCollection.one || $scope.chkCollection.two || $scope.chkCollection.three);
function showRequiredCheckbox(){ 
    return $scope.showRequired && !($scope.form.cb.one 
            || $scope.form.cb.two|| $scope.form.cb.three);
}

#1


0  

Does one of the form.cb group need to be checked? If you need to do more validation, you could do this after your showRequired line, which takes into account showRequired:

是否需要检查form.cb组之一?如果您需要进行更多验证,可以在showRequired行之后执行此操作,该行考虑了showRequired:

<input class="cb" type="checkbox" value="1" ng-model="form.cb.one"
    ng-required="showRequiredCheckbox()" ng-change="handleClick()">one</input>
<input class="cb" type="checkbox" value="2" ng-model="form.cb.two"
   ng-required="showRequiredCheckbox()" ng-change="handleClick()">two</input>...

And js:

$scope.showRequired = !($scope.chkCollection.one || $scope.chkCollection.two || $scope.chkCollection.three);
function showRequiredCheckbox(){ 
    return $scope.showRequired && !($scope.form.cb.one 
            || $scope.form.cb.two|| $scope.form.cb.three);
}