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.

2
  • what did you try till now? Commented Oct 22, 2015 at 20:47
  • I had tried using ng-class="{ 'has-error': userForm.email.$invalid }" and ng-class="{ 'has-error': userForm.email.$error.required }" and ng-style also. Commented Oct 22, 2015 at 20:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I had tried using ng-class="{ 'has-error': userForm.email.$invalid }". but it always add class 'has-error' either validation fails or not.
Updated my answer. Don't use ng-class, see the link.
Thanks Man !! It seems it did work. Bundle of thanks :)
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.