【问题标题】:angular form submission not checking for validation of form角度表单提交不检查表单的验证
【发布时间】:2016-02-18 19:00:35
【问题描述】:

当我点击提交按钮时,表单被提交而不是验证必填字段。

标记

<!DOCTYPE html>
<html lang="en" ng-app="myApp" ng-controller="myCtrl">

<head>
    <meta charset="UTF-8">
    <title>HTML 5</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body>
    <div id="container">
        <p ng-show="msg"> {{ msg }}</p>
        <form name="myForm" novalidate ng-submit="valid()">
            <p> Name <input type="text" name="name" id="" ng-model="user.name" ng-required=true></p>
            <p ng-show="myForm.name.$invalid && myForm.name.$touched">name is required</p>
            <p> Email <input type="email" name="email" id="" ng-model="user.email" ng-required=true> </p>
            <p ng-show="myForm.email.$invalid && myForm.email.$touched">must be a valid email</p>

            <input type="submit" value="submit">
        </form>
    </div>
    <script>
      angular.module('myApp', [])
         .controller('myCtrl', ['$scope', function($scope) {
            $scope.valid = function() {
            $scope.msg = "form submitted";
         }
      }]);
    </script>
</body>
</html>

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: javascript angularjs forms


    【解决方案1】:

    如果表单被验证,调用函数的最短方法如下所示,只有当表单有效时才会触发有效的function

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

    或者其他方法是检查$scope 中的myForm 对象,因为当您在表单上提供name="myForm" 时,Angular 确实会在范围内创建一个对象,该对象具有该对象内的所有信息字段信息。

    $scope.valid = function(){
       if($scope.myForm.$valid){
          //form is valid
          //do $http.post call if you wanted to submit form data
       }
       else {
          alert('form is invalid');//some how notify user that form is invalid.
       }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用以下方法禁用提交按钮:

      ng-disabled="boolean expression"

      在你的情况下,它会很简单:

      &lt;input type="submit" value="submit" ng-disabled="!myForm.$valid"&gt;

      【讨论】:

        【解决方案3】:

        试着放:

        $scope.valid=function() {
          if ($scope.myForm.isValid()) $scope.msg="form submitted";
          else $scope.msg="form with errors";
        }
        

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-07-03
          • 1970-01-01
          • 1970-01-01
          • 2012-06-29
          • 2015-11-12
          • 1970-01-01
          • 1970-01-01
          • 2020-02-12
          相关资源
          最近更新 更多