I want to warn the user if the form field is touched and left empty. I can check if the empty field is touched with $pristine
. But if I preload form data from $scope
, $pristine
doesn't work. Also, I don't want to use required
parameter, I only want to inject warning-style with ng-class
.
<div ng-class="{'has-warning': !form.name.$pristine}">
<input type="text" name="name" ng-model="people.name">
</div>
I want to warn the user if the form field is touched and left empty. I can check if the empty field is touched with $pristine
. But if I preload form data from $scope
, $pristine
doesn't work. Also, I don't want to use required
parameter, I only want to inject warning-style with ng-class
.
<div ng-class="{'has-warning': !form.name.$pristine}">
<input type="text" name="name" ng-model="people.name">
</div>
Share
Improve this question
asked May 9, 2015 at 13:14
PekkaPekka
9992 gold badges12 silver badges22 bronze badges
2
-
seems like what you are describing is
required
so why don't you want to use it? A css warning display won't validate the field itself – charlietfl Commented May 9, 2015 at 13:42 -
1
I want to validate the form with
required
but this field is not necessary and I only want to warn the user. – Pekka Commented May 9, 2015 at 17:28
3 Answers
Reset to default 5There are several state properties set on the ngModel described here. You may want to consider using form.name.$dirty or form.name.$touched instead.
edit
Try using:
ng-class="{'has-warning': form.name.$touched && people.name.length === 0}"
You can try using ngFocus:
Specify custom behavior on focus event.
https://docs.angularjs/api/ng/directive/ngFocus
<div ng-class="{'has-warning': !form.name.isValid}">
<input type="text" name="name" ng-model="people.name" ng-focus="form.name.isValid = people.name ? true : false">
</div>
I would suggest to use :
form.name.$touched && form.name.$invalid
it should work