简体   繁体   English

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

[英]How to use angular to implement checkbox group required validation?

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. 我打算更改ng-required属性以进行单击复选框的验证,但是由于它是模板,因此它可能具有页面其他位置使用的相同变量名($ scope.showRequired),这可能会影响其他必填字段。 How to solve this problem? 如何解决这个问题呢? Thanks 谢谢

Does one of the form.cb group need to be checked? 是否需要检查form.cb组之一? If you need to do more validation, you could do this after your showRequired line, which takes into account showRequired : 如果您需要进行更多验证,则可以在showRequired行之后执行此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: 和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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM