gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:35:30 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com