繁体   English   中英

Angular ngMessage:在表单提交时验证

[英]Angular ngMessage: Validate on form submit

在这个插件中有一个带有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');

  };      
});

您需要使用例如ng-if等条件显示验证消息

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()">

基于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()">

对我来说,只需要在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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM