AngularJS - 对表单提交执行额外验证

AngularJS - perform extra validation on form submit

我在谷歌上搜索了一段时间,似乎找不到适合我的具体案例的答案。我已经找到了进行实时验证的方法,但我想在用户单击 "submit" 后将其与一些自定义验证结合起来。我想让用户仍然点击提交,即使它无效,但我会在代码中取消提交。取以下代码:

<form name="cashForm" id="cashForm" novalidate>
  <input type="text" id="name" required /> //
  <input type="number" placeholder="Tax: " required name="tax" id="tax" />
  <input type="number" placeholder="Tip: " required name="tip" id="tip" />
  <button ng-click="submission()" ng-disabled="paymentForm.$invalid">Submit</button>
</form>


//inside controller
this.submission = function() {
  //check if tip + tax is over 20
  //prevent form and show error message if not
  //otherwise allow default behavior
}

所以我只想在 tax/tip 超过 10 时才真正提交表单。如何检查这一点以及如果不符合要求如何阻止表单提交?另外,我会把这个逻辑放在控制器中吗?

它看起来非常接近你对我的要求。只是几件事...

向您的输入控件添加 ng-model 指令以创建您可以在控制器中获取和使用的双向数据绑定:

<form name="cashForm" id="cashForm" novalidate>
    <input id="name" name="name" type="text" ng-model="nameValue" required />
    <input id="tax" name="tax" type="number" ng-model="taxValue" placeholder="Tax: " required   />
    <input id="tip" name="tip" type="number" ng-model="tipValue" placeholder="Tip: " required />
    <button 
        ng-click="submission()" 
        ng-disabled="paymentForm.$invalid"> 
        Submit 
    </button>

$scope 注入您的控制器,以允许您在控制器的 submission 方法中获取那些 ng-model 绑定:

function submission() {

    $scope.errorMsg = "";

    if ($scope.taxValue <= 10) {
        $scope.errorMsg = "tax not greater than 10";
        return;
    }

    if ($scope.tipValue <= 10) {
        $scope.errorMsg = "tip not greater than 10";
        return;
    }

    // If you reached here your post-click validation passed, 
    // so continue to submit the data...

 }

然后您可以使用 ng-if 指令和 css class 突出显示错误消息的指令来显示错误消息:

<div ng-if="!!errorMessage" class="text-danger">
    {{ errorMessage }}
</div>

最后,一旦你在你的控制器中使用 $scope 破解,你可能想阅读关于使用 $scope 的感知弊端并考虑改用控制器作为语法。查看 John Papa 的博客 Post AngularJS's Controller As and the vm Variable