javascript - AngularJS - 防止提交带有必填字段的表单

标签 javascript angularjs html forms ionic-framework

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

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

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

最佳答案

我会看一下 Angular 验证器: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>

关于javascript - AngularJS - 防止提交带有必填字段的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32753400/

相关文章:

javascript - 声明一个 JavaScript 变量来存放 php 变量

javascript - React useEffect 不会阻止重新渲染

javascript - 在 D3 Javascript 中显示 .json map

angularjs - 如何在ng-file-upload中获取上传文件的文件名

html - 如何删除 CSS 网格中的第一个空列?

HTML 电子邮件 - 标题图片未在 Thunderbird 中居中

javascript - 在 Meteor 中,如何仅在用户使用特定外部服务登录时加载 JavaScript?

javascript - 具有多个模板的 AngularJS 指令

html - Twitter Bootstrap 轮播导航显示