AngularJS - 阻止使用必填字段提交表单

时间:2015-09-24 04:32:03

标签: javascript angularjs html5 forms ionic

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

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

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

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

$scope.yourFormName.$valid

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

答案 2 :(得分:0)

I used the ng-submit directive as it triggers form.$submitted and validates ng-required fields properly before submitting.

For the case where you have multiple buttons, for I added an ng-click to each button and simply changed a $scope variable (e.g. $scope.pressedBtn). In the function that ng-submit points to, you could do something like:

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