2014-12-05 23 views
9

這是我目前的驗證設置爲我的形式角度驗證NG-消息後提交併刪除文本

<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)點擊進入空了搜索框 - >它顯示了正確的信息「字段是必須的」

2)開始打字和擦除的文本,而不按回車 - >它再次顯示錯誤消息

這是我不想要的第二種情況......任何想法?

+1

你爲什麼使用'searchForm.searchQuery。$ touched'?這可能是你得到這種行爲的原因。嘗試使用只是'searchForm。$提交' – Anubhav 2014-12-05 14:56:17

+0

擺脫它,只是提交了,但同樣的行爲...它似乎像第一次提交後,表單停留在「已提交」狀態,並且該錯誤消息只顯示文本框是空然後寧願當再次提交 – StevieB 2014-12-05 15:00:23

+0

[這篇文章](http://stackoverflow.com/questions/16759221/angularjs-setpristine-to-reset-form)可能會幫助你。 – Anubhav 2014-12-05 15:02:29

回答

6

也許您的錯誤消息的字段名稱不正確。 由於您沒有提供示例,無法確定您的工作原因。 但是,當我測試時,它工作正常。

<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

+0

同樣的事情發生在你的身上。所以你打,沒有任何文字輸入和輸入消息裏顯示,即「輸入必填字段」,然後只需鍵入的東西並清除文本框的文本和錯誤信息,而不必進入提交 – StevieB 2014-12-09 09:23:43

+0

哦再次顯示,要顯示錯誤消息只有在提交按鈕被按下時?然後,只需在輸入字段中添加'ng-keypress =「searchForm。$ submitted = false」',儘管它不是最好的。我爲此修改了'plnkr'。 – allenhwkim 2014-12-09 14:20:46

+0

僅當文本框爲空並且按下提交按鈕時才顯示消息 – StevieB 2014-12-09 15:11:09

0

我會以不同的方式做到這一點。希望能幫助到你。如果表單無效且髒,它將顯示消息。當用戶提交時,通過將其設置爲原始形式來重置表單。有了這個,你可以將你的$ 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

0

你可以編寫自己的自定義驗證,然後使用if語句來決定驗證什麼。比如你不希望有人在擦除字符時進行任何驗證,你可以編寫驗證器以便它接受一個事件,然後你可以獲得觸發該事件的密鑰的字符代碼,不選擇驗證該char代碼是退格還是刪除。

相關問題