I am building an angular app for which I have some forms set up. I have some fields that are required to be filled before submission. 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 inputs are empty and therefore invalid when instantiated, Angular correctly adds the ng-invalid
class.
A CSS rule you might try:
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 pristine by $scope.formName.setPristine(true)
and something wasn't yet entered and it's invalid then the text turns red
.
Other useful classes for Angular forms (see input for future reference )
ng-valid-maxlength
- when ng-maxlength
passesng-valid-minlength
- when ng-minlength
passesng-valid-pattern
- when ng-pattern
passesng-dirty
- when the form has had something entered since the form loadedng-pristine
- when the form input has had nothing inserted since loaded (or it was reset via setPristine(true)
on the form)ng-invalid
- when any validation fails (required
, minlength
, custom ones, etc)
Likewise there is also ng-invalid-<name>
for all these patterns and any custom ones created.
Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:
input.ng-pristine.ng-invalid { -webkit-box-shadow: none; -ms-box-shadow: none; box-shadow:none; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With