【问题标题】:angular validation - prevent button ng-click() when form is invalid角度验证 - 当表单无效时阻止按钮 ng-click()
【发布时间】:2015-11-13 15:05:45
【问题描述】:

我有一个角形式作为单页应用程序的一部分。 “继续”按钮将用户移动到应用程序的下一部分,并单击 ng。我想防止在单击按钮并且表单无效时发生这种 ng-click,但我不想禁用 Continue 按钮。

示例:用户进入页面并立即单击“继续”按钮而没有提供名字。将显示错误消息“您应该提供名字”,并且用户仍留在页面上。

我该怎么做?这是代码:

<form name="form" novalidate >

<div ng-show="form.FirstName.$touched && form.FirstName.$error.required" class="errorMessage">
    You must enter a first name
</div>

<div class="form-group">
    <label for="firstName" class="form-label">First Name</label>
    <input id="firstName" class="form-control" name="FirstName" ng-model="vm.user.firstName" required />
</div>

<div class="btn-group">
    <button ng-click="vm.next()">Continue</button>
</div>
</form>

【问题讨论】:

标签: angularjs forms validation


【解决方案1】:

只要在函数调用前加上form.$valid &amp;&amp;即可:

<form name="form" novalidate >

<div ng-show="form.FirstName.$touched && form.FirstName.$error.required" class="errorMessage">
    You must enter a first name
</div>

<div class="form-group">
    <label for="firstName" class="form-label">First Name</label>
    <input id="firstName" class="form-control" name="FirstName" ng-model="vm.user.firstName" required />
</div>

<div class="btn-group">
    <button ng-click="form.$valid && vm.next()">Continue</button>
</div>
</form>

【讨论】:

  • 效果很好,有没有办法在点击继续按钮时显示错误消息?
  • 检查用户是否已经尝试过:ng-show="tried &amp;&amp; form.FirstName.$touched &amp;&amp; form.FirstName.$error.required" + ng-click="tried = true; form.$valid &amp;&amp; vm.next()"
  • 但是由于您现在要向视图添加大量逻辑,您应该考虑将其放入控制器函数中。
【解决方案2】:

按钮被禁用或可点击,你不能同时拥有它。

您可以在控制器中为 vm.next() 执行的操作是:

myApp.controller('Page1Controller'),  ['$scope', function ($scope)
{
    $scope.vm = {};

    $scope.vm.next = function()
    {
        if (! $scope.vm.isFormValid())            
            return;            
        //move to the next page with your current code
        ...
    }

    $scope.vm.isFormValid()
    {
        $scope.vm.shouldShowError = $scope.form.valid; //add vm.shouldShowError to your error message ng-show in the view so it will display only after clicking continue
        return $scope.form.valid;
    }
}]);

【讨论】:

  • 如果按钮不应该将您带到下一页/表单/等,我同意。它应该以这种方式向用户显示该按钮将不起作用。最好使用vm.form.$invalid禁用按钮。
  • 我需要写一个 isFormValid() 函数吗?我想可能有一些内置的东西来确定这一点。
  • 不,您只能使用 $scope.form.valid。我发现在较大的表单中,我几乎总是需要进行某种自定义验证,因此我养成了始终包含 isValid 函数以提高可读性的习惯。
  • 在定义 $scope 时遇到问题,因为我目前没有在我的控制器中使用它。
  • 在我的回答中添加了带有 $scope 的示例控制器声明
猜你喜欢
  • 2018-08-22
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
相关资源
最近更新 更多