【问题标题】:Form validation in AngularJS not working as expectedAngularJS 中的表单验证无法按预期工作
【发布时间】:2014-02-25 15:23:08
【问题描述】:

我有一个角形。我正在尝试对必填字段进行一些验证,例如在 this nice 教程中,它说 angular 具有“内置”此功能。但是-它对我不起作用。当我在未填写字段的情况下提交表单时,什么也没有发生。谁能明白为什么?

    <form id = "myForm" name="myForm" novalidate>

                        <div class="form-group" ng-class="{ 'has-error' : myForm.name.$invalid && !myForm.name.$pristine && submitted }">
                        <input type="text" name="name" class="form-control" ng-model="company.name" required>
                        <p ng-show="myForm.name.$invalid && !myForm.name.$pristine" >Your firm's name is required.</p>
                        </div>
                        <br />
                        <br />
                        <div class="form-group" ng-class="{ 'has-error' : myForm.address.$invalid && !myForm.address.$pristine && submitted }">
                        <input type="text" class="form-control" id = "address" name="address"  ng-model="company.address" required>
                         <p ng-show="myForm.address.$invalid && !myForm.address.$pristine" class="help-block">Your address is required.</p>
                        </div>

<button type="submit" ng-click= "createAccount()" class="btn btn-small btn-primary">GO

    </button>

        </form>

我还在我的 createAccount() 函数中包含了$scope.submitted = true;

【问题讨论】:

标签: forms angularjs validation


【解决方案1】:

请记住,AngularJS 是一个客户端框架。您的验证必须在您提交内容之前执行。

ng-disabled 添加到您的提交按钮:

<button type="submit" ng-disabled="myForm.$invalid" ng-click= "createAccount()" class="btn btn-small btn-primary">GO</button>

或者在您所指的教程示例中检查createAccount() 函数中的验证状态:

if (!$scope.myForm.$valid) {
   alert('Something is wrong');
}

【讨论】:

  • 谢谢,这是处理验证的一种方式——但在本教程中,它表明可以先提交表单,然后用错误消息突出显示所有必填字段。
  • 好的,我想我明白了你想要什么。除了@Chandermani 发布的链接,还请查看stackoverflow.com/questions/17452247/…
猜你喜欢
  • 2017-07-19
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 2014-04-14
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
相关资源
最近更新 更多