簡體   English   中英

提交和刪除文本后,角度驗證NG消息不顯示

[英]Angular Validation NG-message dont show required after submit and erase text

這是我當前為表單設置的驗證

<ng-messages for="searchForm.$error" ng-if="searchForm.$submitted">
  <ng-message when="required" class="error-message">This search field is required.</ng-message>
</ng-messages>

和我的形式

<form role="form" ng-submit="searchForm.$valid && searchcode()" name="searchForm" novalidate>

它工作正常。

但這是我不喜歡這種情況

1)在空搜索框上按Enter鍵 - >它顯示正確的消息“字段是必需的”

2)開始鍵入和刪除文本而不按Enter鍵 - >它再次顯示錯誤信息

這是我不想要的第二個場景......任何想法?

也許您的錯誤消息的字段名稱不正確。 無法說明你為什么不工作的確切原因,因為你沒有提供一個例子。 但是,當我測試時,它工作正常。

 <form ng-controller="MyCtrl" role="form" name="searchForm" novalidate
    ng-submit="searchcode()">
    <input type="text" ng-model="field" name="myField" 
      ng-keypress="searchForm.$submitted=false"
      required minlength="5" />
    <ng-messages ng-if="searchForm.$submitted"
      for="searchForm.myField.$error">
      <ng-message when="required" class="error-message">
        This search field is required.
      </ng-message>
    </ng-messages>
  </form>

http://plnkr.co/edit/56koY7YxPDVFe4S26x9N?p=preview

我將以不同的方式做到這一點。 希望能幫助到你。 如果表單無效且臟,它將顯示消息。 當用戶提交時,通過將其設置為原始狀態來重置表單。 這樣,您可以將$ scope.field重置為空並且不顯示錯誤消息。

<form ng-controller="MyCtrl" role="form" name="searchForm" novalidate ng-submit="searchcode()">
   <input type="text" ng-model="field" name="myField" required minlength="5" />
   <p class="error-message" ng-show="!searchForm.$valid && searchForm.$dirty">
     This search field is required.
   </p> 
   <ul>
      <li>$submitted : {{searchForm.$submitted}}
      <li>$valid: {{searchForm.$valid}}
      <li>$dirty:  {{searchForm.$dirty}} 
   </ul>
</form>

在提交時,通過將表單設置為原始來重置表單。

$scope.searchcode = function() {
    $scope.searchForm.$setPristine();
    $scope.field="";
    console.log('submitted');
  }

http://plnkr.co/edit/m0cCmOAtY2J8fhSv0DVg?p=preview

您可以編寫自己的自定義驗證器,然后使用if語句來決定要驗證的內容。 例如,由於你不希望在一個人擦除字符時進行任何驗證,你可以編寫驗證器以便它接受一個事件,然后你可以得到觸發事件的密鑰的字符代碼,選擇不驗證該char代碼何時表示退格或刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM