javascript AngularJS - 如果表单无效,则防止提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27998744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:16:31  来源:igfitidea点击:

AngularJS - Prevent submission of a form if it is invalid

javascriptangularjsformsangularjs-forms

提问by rwacarter

I have created an isolated case of my issue: http://plnkr.co/edit/6LXW5TG76LC9LNSrdpQC

我为我的问题创建了一个孤立的案例:http: //plnkr.co/edit/6LXW5TG76LC9LNSrdpQC

Here is the code of the isolated case:

这是孤立案例的代码:

<!DOCTYPE html>
<html ng-app="App">

  <head></head>

  <body ng-controller="ExampleController">

    <form name="form" ng-submit="submit()" novalidate>
      <input type="number" name="number" ng-model="number" required><br>
      <span ng-show="form.number.$error.required && form.number.$touched">Required<br></span>
      <span ng-show="form.number.$error.number">Not a number<br></span>
      <input type="submit">
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>

    <script>

      var App = angular.module('App', []);

      App.controller('ExampleController', function($scope) {

        $scope.submit = function() {
          alert('send to server: ' + $scope.number);
        }

      });

      App.run();

    </script>

  </body>

</html>

Basically, the example contains a number field, and beneath it are error messages that show when the input is invalid (empty or not a number).

基本上,该示例包含一个数字字段,其下方是显示输入无效(空或不是数字)的错误消息。

But the form will still submit, and although the field value is set to 'undefined' if it is not valid, I would prefer a way of checking if the form is valid before sending to the server (the alert box in this example).

但是表单仍然会提交,尽管如果字段值无效,则该字段值设置为“未定义”,但我更喜欢在发送到服务器之前检查表单是否有效的方法(本例中的警报框)。

So my question is - In AngularJS, is there a way of checking if a form is valid from within a controller? Or another way to prevent a form from submitting if it is invalid?

所以我的问题是 - 在 AngularJS 中,有没有办法从控制器中检查表单是否有效?或者另一种防止表单无效的方法?

回答by Pankaj Parkar

Better do change in ng-submitexpression to

最好改变ng-submit表达方式

ng-submit="form.$valid && submit()"

Best use of angular directive expression.

角度指令表达式的最佳使用。

回答by Arūnas Smaliukas

http://plnkr.co/edit/kqLUJpjt0n0anJxzm6en?p=preview

http://plnkr.co/edit/kqLUJpjt0n0anJxzm6en?p=preview

what you need is

你需要的是

if ($scope.form.$valid) {
    //submit to server
}

where formis form name

form表格名称在哪里

<form name="form"...

回答by kinetix

You can try with ng-disableddirective

您可以尝试使用ng-disabled指令

      <button type="submit" ng-disabled='number==null'>Submit</button>

In that way you can avoid adding additional code

这样你就可以避免添加额外的代码