AngularJS 当一些元素还没有被触及时,表单验证转换为有效

AngularJS Form validation transition to valid when some elements are not even touched yet

我有一个保存按钮,只有在提供了所有表单数据并且表单是 有效 时才会启用。我不明白为什么带宽选项没有 selected 而表格变得有效。 myForm.$valid 过渡到 true ... 它应该保持 false

<button id="save-create-account-modal" type="submit" class="btn btn-success"
    ng-disabled="!myForm.$valid || $ctrl.disableButton" ng-click="$ctrl.accessPointSave($ctrl.accessPoint)">
    Save
</button>

带宽select菜单

<div class="col-xs-3">
    <div class="form-group" ng-class="{ 'has-error': myForm.uplink.$touched && myForm.uplink.$invalid }">
        <label for="uplink" class="required">
            <translate>GENERAL.UPLINK.value</translate>
        </label>
        <select id="edit-service-plan-uplink-select" class="form-control" name="uplink"
            ng-model="$ctrl.accessPoint.uplink"
            ng-options="bandwidth.value as bandwidth.option for bandwidth in $ctrl.uplinks" required>
        </select>
    </div>

    <span class="message error" ng-messages="myForm.uplink.$error" ng-if="myForm.uplink.$touched">
        <p ng-message="required">
            <translate>GENERAL.FORM_VALIDATIONS.REQUIRED_FIELD.value</translate>
        </p>
    </span>
</div>

<div class="col-xs-3">
    <div class="form-group"
        ng-class="{ 'has-error': myForm.downlink.$touched && myForm.downlink.$invalid }">
        <label for="downlink" class="required">
            <translate>GENERAL.DOWNLINK.value</translate>
        </label>
        <select id="edit-service-plan-downlink-select" class="form-control" name="downlink"
            ng-model="$ctrl.accessPoint.downlink"
            ng-options="bandwidth.value as bandwidth.option for bandwidth in $ctrl.downlinks" required>
        </select>
    </div>

    <span class="message error" ng-messages="myForm.downlink.$error" ng-if="myForm.downlink.$touched">
        <p ng-message="required">
            <translate>GENERAL.FORM_VALIDATIONS.REQUIRED_FIELD.value</translate>
        </p>
    </span>
</div>

如何进一步调试?


已更新

我还尝试在与我的 <select> 标签相同的行中添加 required

still not working as expected

请将 $dirty 检查与 $valid 一起包括在内。

($scope.form[field].$dirty && $scope.form[field].$valid){
      //your code
}

你也可以试试ng-required。

例如当 select 中的值不是选项中的值时,就会发生这种情况。

如果你想调试 - 所需的验证器在这里:https://github.com/angular/angular.js/blob/master/src/ng/directive/validators.js