Reputation: 3614
I have a form with two fields:
<form name="form">
<input type="email" ng-model-options="{ updateOn: blur }" required />
<input type="password" ng-model-options="{ updateOn: blur }" required />
<div ng-show="form.password.$error.required">Password required</div>
</form>
The error div is always displayed when the password field is empty - I only want it to display if the password has been focused and then blurred. Is there a simple change I can make to enable this?
Upvotes: 5
Views: 560
Reputation: 36624
You'd want something like $dirty
(changed from default value) or $touched
(blurred at least once, probably what you want, based on your model options).
form name="form">
<input type="email" ng-model-options="{ updateOn: blur }" required />
<input type="password" ng-model-options="{ updateOn: blur }" required />
<div ng-messages="form.password.$error" ng-if="form.password.$touched">
<div ng-message="required">Password required</div>
</div>
</form>
I used ng-messages
here because it's neat, but you don't have to use it, you can just add the condition to your ng-show
/ ng-if
.
Upvotes: 0
Reputation: 25807
This should work using the $pristine
property.
<div ng-show="!form.password.$pristine && form.password.$error.required">Password required</div>
$pristine
returns true if user has not interacted with the control yet.
https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
Upvotes: 1
Reputation: 2400
<div ng-show="form.password.$error.required && form.password.$dirty">Password required</div>
You can do this by adding condition of dirty field. So if the field will be dirt then only it will show error
Upvotes: 2