如何在AngularJS中显示提交错误并停止提交表单而不禁用提交按钮?

时间:2017-08-23 05:52:55

标签: angularjs validation angularjs-ng-form angular-forms ng-submit

我想验证我的表单是否有错误提交空字段我该怎么做我的控制器?

<form id="login-form" name="LoginForm" action="/home" method="get" class="loginform" role="form" novalidate ng-submit="LoginValidator()">

    <input type="email" name="Email" id="email" tabindex="1"
           ng-model="login.email"
           ng-pattern="/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/"
           placeholder="Email" ng-required="true">
    <span style="color:red; display:block; text-align:center;"
          ng-show="LoginForm.Email.$dirty && LoginForm.Email.$error.pattern">
     * Please Enter Valid Email</span>
    <span style="color:red; display:block; text-align:center;"
          ng-show="LoginForm.Email.$submitted && LoginForm.Email.$error.required">
     * Email required</span>

    <input type="password" name="password" ng-minlength="8" id="password"
           tabindex="2" ng-model="login.password"
           placeholder="Password" ng-required="true">
    <div ng-show="LoginForm.password.$dirty && LoginForm.password.$invalid">
      <small style="color:red; display:block; text-align:center;">
        * Invalid Password</small>
    </div>
    <input type="submit" value="LOG IN" />

</form>

它显示第一个错误但未显示$ submitted

的错误

我为什么要在这里做?

var app = angular.module('qec', []);
app.controller('login' ,['$scope' , function ($scope) {
    $scope.LoginValidator = function (isValid) {
    };
}]);

1 个答案:

答案 0 :(得分:0)

在submit的函数内验证控制器中表单的$ valid属性。

<强>更新

$scope.LoginValidator = function ($event) {
  $event.preventDefault();
  if($scope.LoginForm.$valid){
    console.log("valid");
  }else{
    console.log("invalid");
    console.log($scope.LoginForm.$error.require);
    if($scope.LoginForm.Email.$invalid){
      $scope.mailRequire = true;
    }
    if($scope.LoginForm.password.$invalid){
      $scope.passRequire = true;
    }
  }
  };

也用于显示所需的电子邮件错误。像这样改变HTML

<span style="color:red; display:block; text-align:center;"
      ng-show="mailRequire">* Email required</span>

这是plnkr