4
<label class="item item-input margin5px">
<input type="email" name="email"  class="form-control" placeholder="Email" ng-model="user.email" ng-minlength=5 ng-maxlength=100   required>
</label>

I have minlength, maxlength and required validation on my email field. I want to add a class 'has-error' or add a certain style if any one of these validation fails. Any help would be much appreciated.

Haseeb Mazhar Ranga
  • 555
  • 1
  • 5
  • 16

2 Answers2

3

Angular will already do that for you. If the validation fails, the input will have the class ng-invalid, which you can style via CSS.

See example from Using CSS classes on AngularJS Forms:

input.ng-invalid.ng-touched {
    background-color: #FA787E;
}

this CSS will only apply if the input is invalid and it has been edited.

Don't use ng-class stuff, as said, Angular adds the correct classes for you.

Matsemann
  • 21,083
  • 19
  • 56
  • 89
0

If you are using bootstrap, the has-error class is a good idea.

Your input should be in a form and you can use the ng-class directive on a parent div.

Angular allow you to check a form input that way : myForm.email.$invalid

If you want the style to be applied only once the user has 'touched' the input, you can test myForm.email.$invalid && myForm.email.$dirty

<form name="myForm">
<div class="form-group" ng-class="{'has-error':myForm.email.$invalid && myForm.email.$dirty}">
    <label class="item item-input margin5px"></label>
    <input type="email" name="email"  class="form-control" placeholder="Email" ng-model="user.email" ng-minlength=5 ng-maxlength=100   required>        
</div>
</form>