Spearfisher Spearfisher - 2 months ago 11x
AngularJS Question

Angular automatically add 'ng-invalid' class on 'required' fields

I am building an angular app for which I have some forms set up.
I have some fields that are required to be field before submition. Therefore I have added 'required' on them:

<input type="text" class="form-control" placeholder="Test" ng-model="data.test" required>

However when I launch my app, the fields are displayed as 'invalid' and the classes 'ng-invalid' and 'ng-invalid-required' even before the submit button has been click or before the user has typed anything in the fields.

How can I make sure that thoses 2 classes are not added immediately but either once the user has submitted the form or when he has typed something wrong in the corresponding field?


Since the are indeed invalid to begin with, angular's logic is correct in putting the invalid classes to start.

As a css rule example you might try putting:

input.ng-dirty.ng-invalid {
  color: red

Which basically states when the field has had something entered into it at some point since the page loaded (and wasn't reset to be pristine via $scope.formName.setPristine(true) ) and something entered and it's invalid then the text turns red.

Other useful classes for Angular forms (see input for future reference )

ng-valid-maxlength - Put when ng-maxlength passes
ng-valid-minlength - Put when ng-minlength passes
ng-valid-pattern - Put when ng-pattern passes
ng-dirty - Put when the form has had something entered since the form loaded
ng-pristine - Put when the form input has had nothing inserted since loaded (or it was reset via setPristine(true) on the form)
ng-invalid - Put when any validation fails (required, minlength, custom ones, etc)

Like wise there is also ng-invalid- for all these patterns and any custom ones created.