使用form.submit验证复选框部分

Using form.submit to validate checkbox section

本文关键字:复选框部 验证 submit form 使用      更新时间:2023-09-26

我有一个名称传递给控制器的表单,当表单为$valid时,我将继续处理数据。这曾经适用于单选按钮,但当我切换到复选框时,只有在选中所有复选框时才能通过验证。如何做到这一点,选择1将使表单有效?供参考的代码片段:

<form name="snippetForm" ng-submit="vm.submitForm(snippetForm)" novalidate>
    <input type="checkbox" ng-model="vm.destination.1" ng-true-value="'1'" name="location" required >
    <input type="checkbox" ng-model="vm.destination.2" ng-true-value="'2'" name="location" required >
    <input type="checkbox" ng-model="vm.destination.3" ng-true-value="'3'" name="location" required >
</form>
vm.submitForm = function(form) {
    if(form.$valid) {
        console.log('Passes only when all checkboxes from form.location are selected')
    }
}

我在每个复选框上添加了一个ng-change表达式。如果未选中任何复选框,表达式将使表单无效。

<form name="snippetForm" ng-submit="vm.submitForm(snippetForm)" novalidate>
    <input type="checkbox" ng-model="vm.destination1" ng-true-value="'1'" name="location" ng-change="{{(!vm.destination1 && !vm.destination2 && !vm.destination3) ? (snippetForm.$valid = false) : (snippetForm.$valid = snippetForm.$valid)}}" >
    <input type="checkbox" ng-model="vm.destination2" ng-true-value="'2'" name="location" ng-change="{{(!vm.destination1 && !vm.destination2 && !vm.destination3) ? (snippetForm.$valid = false) : (snippetForm.$valid = snippetForm.$valid)}}" >
    <input type="checkbox" ng-model="vm.destination3" ng-true-value="'3'" name="location" ng-change="{{(!vm.destination1 && !vm.destination2 && !vm.destination3) ? (snippetForm.$valid = false) : (snippetForm.$valid = snippetForm.$valid)}}" >
</form>