Reputation: 6533
This is my current validation set up for my form
<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>
and my form
<form role="form" ng-submit="searchForm.$valid && searchcode()" name="searchForm" novalidate>
It works fine.
But here is what I don't like this scenario
1) Hit Enter on empty searchbox - > it shows the correct message "Field Is Required"
2) Start Typing and Erase Text without hitting enter - > it shows error message again
It's the second scenario I dont want...any ideas ?
Upvotes: 9
Views: 12810
Reputation: 8130
I will do this in different way. Hope it helps. It will show the messages if the form is not valid and dirty. When the user submits, reset the form by setting it to be pristine. With this, you can reset you $scope.field to empty and not showing error messages.
<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>
On submit, reset the form by setting it to be pristine.
$scope.searchcode = function() {
$scope.searchForm.$setPristine();
$scope.field="";
console.log('submitted');
}
http://plnkr.co/edit/m0cCmOAtY2J8fhSv0DVg?p=preview
Upvotes: 0
Reputation: 1343
You could write your own custom validator, and then use an if statement to decide what to validate. Since for instance you don't want there to be any validation done when a person is erasing characters, you could write the validator so that it takes an event and then you can get the char code of the key that fired the event, opting not to validate when that char code represents either backspace or delete.
Upvotes: 0
Reputation: 27738
Maybe your field name for the error message is not right. Cannot tell the exact reason why yours not work because you did not provide an example. However, when I tested, it works fine.
<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
Upvotes: 6