【问题标题】:AngularJS - prevent submissions of form with required fieldsAngularJS - 防止提交带有必填字段的表单
【发布时间】:2015-12-21 14:05:48
【问题描述】:

我有一个 AngularJS 表单,里面有 3 个必填字段(使用 ng-required)。无需触摸表单上的任何内容,只需按下“提交”按钮 (ng-click="submit"),我如何触发对必填字段的验证AND 阻止表单提交?我试过这样做:

ng-required="form.$submitted && !firstName"

这会触发验证,但也会提交表单,即使表单在技术上是 $invalid??

【问题讨论】:

  • 尝试在提交按钮中添加 'ng-disabled=firstname.trim().length
  • 对于角度表单验证,您可以尝试此链接stackoverflow.com/questions/32323910/…
  • 似乎我见过的唯一其他解决方案是使用 angular.forEach 循环在提交时以编程方式将每个必需的输入字段设置为 $dirty 状态。

标签: javascript angularjs html forms ionic


【解决方案1】:

由于您提到您正在对单个元素进行验证,并且不知道检查整个表单是否有效。您可以使用以下条件来检查表单是否有效

$scope.yourFormName.$valid

使用上述条件检查表单是否有效。只有当表单内所有必需的验证都有效时,上述条件才会成立。希望这就是你要找的东西

【讨论】:

    【解决方案2】:

    我会看看 angular-validator:https://github.com/turinggroup/angular-validator。它非常有用,并且真正精简了您的验证代码。 ng-Message 很好,但你最终会维护更多的 HTML,因此它看起来会是更多的手表。

      <form name="categoryForm" id="categoryForm" class="smart-form" angular-validator angular-validator-submit="save(true)" novalidate autocomplete="off">
          <fieldset>
            <section ng-class="{ 'has-error' : categoryForm.title.$invalid}">
              <label class="label">Title</label>
              <label class="input">
                <input name="title" type="text" ng-model="category.title" id="title" placeholder="Title" required
                       validate-on="dirty" required-message="'Title is required'">
              </label>
            </section>
            <section ng-if="isAdmin()">
              <div class="row">
                <section class="col col-6" >
                  <label class="checkbox">
                    <input type="checkbox" name="checkbox" ng-model="category.isGlobal">
                    <i></i><span>Global</span></label>
                </section>
              </div>
            </section>
          </fieldset>
          <footer>
            <button  type="submit" class="btn btn-primary" ng-disabled="(categoryForm.$dirty && categoryForm.$invalid) || categoryForm.$pristine">
              Submit
            </button>
          </footer>
        </form>
    

    【讨论】:

    • 我去看看。谢谢。
    • 我最终改用了 ng-submit。我没有意识到它会触发验证。
    • 太好了,发布您的答案并将其标记为已回答。下次发布您的代码,以便人们更轻松地查看和提供建议。
    【解决方案3】:

    我使用了 ng-submit 指令,因为它会触发 form.$submitted 并在提交前正确验证 ng-required 字段。

    对于您有多个按钮的情况,我为每个按钮添加了一个 ng-click 并简单地更改了一个 $scope 变量(例如 $scope.pressedBtn)。在 ng-submit 指向的函数中,您可以执行以下操作:

    if ($scope.pressedBtn === 'button1') {
        // submit
    }
    else if ($scope.pressedBtn === 'button2') {
        // save
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      相关资源
      最近更新 更多