Angular ngMessage:在表单提交时验证

时间:2016-01-19 10:54:16

标签: angularjs

在这个plunk中有一个带有ngMessage验证的表单。这就是我想要实现的目标:

  • 向用户显示表单时,不应显示任何错误消息
  • 在模糊时,如果字段有错误,则应显示消息
  • 提交表单时,如果有任何字段存在错误,则应显示错误消息。

在插件中我有两个问题:(1)最初显示表单时显示消息,(2)当没有错误消息且用户点击按钮时,表单未提交。代码有什么问题?

HTML

<form name="myForm" novalidate>
  <label>
    Enter your name:
    <input type="text"
           name="myName"
           ng-model="name"
           ng-minlength="5"
           ng-maxlength="20"
           required />
  </label>

  <div ng-messages="myForm.myName.$error" style="color:red" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
  </div>

  <button type="submit" 
  ng-submit="myForm.$valid && submitForm()">Submit</button>
</form>

的Javascript

var app = angular.module('ngMessagesExample', ['ngMessages']);
app.controller('nameController', function ($scope) {

  $scope.submitForm = function() {
    alert('Form submitted - fields passed validation');

  };      
});

3 个答案:

答案 0 :(得分:11)

您需要使用条件显示验证消息,例如NG-如果

HTML:

<div ng-if="submitted || myForm.myName.$dirty" 
    ng-messages="myForm.myName.$error" style="color:red" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
</div>

使用Javascript:

$scope.submitForm = function() {
    $scope.submitted = true;
    if (myForm.$valid) {
        alert('Form submitted - fields passed validation');
    }
};  

并从按钮移动ng-submit以形成标签,如:

<form name="myForm" novalidate ng-submit="submitForm()">

答案 1 :(得分:3)

基于Kwarc的anwser,这里有一点改进,因为您可以避免使用$scope变量来了解您的表单是否已提交。它还确保在错误消息显示方面有更好的行为。

HTML:

<div ng-if="myForm.myName.$invalid && (myForm.$submitted || myForm.myName.$touched)" 
   ng-messages="myForm.myName.$error" style="color:red" role="alert">
   <div ng-message="required">You did not enter a field</div>
   <div ng-message="minlength">Your field is too short</div>
   <div ng-message="maxlength">Your field is too long</div>
</div>

使用Javascript:

$scope.submitForm = function() {
   if (myForm.$valid) {
       alert('Form submitted - fields passed validation');
   }
};  

myForm.$submitted将自动设为true

最后,在表单标记上应用相同的表单提交方法:

<form name="myForm" novalidate ng-submit="submitForm()">

答案 2 :(得分:0)

对我而言,只需在ng中使用 - 如果表单的$ submit状态(例如是准系统):

// and in the submit btn

scope.submit = function() {
  scope.myForm.$setSubmitted();
  if (scope.myForm.$valid) {
    // do something
  }
}
<div ng-if="myForm.$submitted || myForm.attr.$touched" ng-messages="myForm.attr.error">
  <!-- messages with ngMessages -->
</div>