Angular Form - Required with ng-model options

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 dialog is always displayed when the password field is empty - I want it to be displayed only if the password has been focused and then blurred. Is there a simple change I can make to enable this?

+5
source share
3 answers
 <div ng-show="form.password.$error.required && form.password.$dirty">Password required</div> 

You can do this by adding a dirty field condition. Therefore, if the field is dirty, then only it will show an error

+2
source

This should work using the $pristine property.

 <div ng-show="!form.password.$pristine && form.password.$error.required">Password required</div> 

$pristine returns true if the user has not yet interacted with the control.

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

+1
source

You need something like $dirty (changed from the default) or $touched (blurred at least once, maybe what you want based on your model options).

Example

 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 is neat, but you do not need to use it, you can just add a condition to your ng-show / ng-if .

References

0
source

All Articles