簡體   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