0

This is my first time using bootstrap and angularJS and I have created a login form . If my username does not have the correct length I display an error under the input . However I also want to change the input border color to red if I have an error displayed and I do not know how to do it . If I can do this for a single input I can use it everywhere

My code for a username input :

      <form name= "logForm">
        <div class="form-group">
          <label for="username">Username:</label>
          <input type="username" class="form-control" id="uname" placeholder="Enter username" name="uname" 
                 ng-minlength= "10" ng-maxlength = "15" ng-model = "uname" required/>

          <span style= "color: #4CAF50" ng-show = "logForm.uname.$valid">Valid</span>
          <span style= "color:red" ng-show= "logForm.uname.$touched && logForm.uname.$error.minlength">
            Min length is 10 
          </span>
          <span style= "color:red" ng-show= "logForm.uname.$touched && logForm.uname.$error.maxlength">
            Max length is 15 
          </span>     

        </div>
     </form>

So I need to find a way that whenever the error shows up my input border is red and when I have valid input the border must be green .

2 Answers 2

1

This can be done using ng-class or ng-style: solution using ng-style:

<input type="username"
    class="form-control"
    ng-style="!(!(uname.length < 10) && !(uname.length > 15)) && {"border" : "1px solid red"} "
    id="uname"
    placeholder="Enter username"
    name="uname"
    ng-minlength="10"
    ng-maxlength="15"
    ng-model="uname"
    required
/>
1

You can add class to element using ng-class. More information about this directive is available under documentation: https://docs.angularjs.org/api/ng/directive/ngClass

In your case you want to add some class to form when error is visible. All you have to do is add something like ng-class="{ 'is-invalid': logForm.uname.$touched && logForm.uname.$error.minlength }" into your input. (Please note that class is-invalid is official bootstrap input error class, but can be vary in different versions: https://getbootstrap.com/docs/4.0/components/forms)

<input type="username"
    ng-class="{ 'is-invalid': logForm.uname.$touched && logForm.uname.$error.minlength }"
    class="form-control"
    id="uname"
    placeholder="Enter username"
    name="uname"
    ng-minlength="10"
    ng-maxlength="15"
    ng-model="uname"
    required
/>

If you just want to add some style instead of class, you can use ng-style directive: https://docs.angularjs.org/api/ng/directive/ngStyle

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.