Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: change border color for error in form validation

Tags:

html

css

angular

Trying to change the border color for error message. this is my html code

<div class="form-group">
  <label>Name:</label>
  <div class="wpr">
    <div class="wpr__icon">
      <i class="fa fa-user"></i>
    </div>
    <input #name="ngModel" id="name" name="name" type="text" class="form-control text-line" [(ngModel)]="PersonInfo.name"
      pattern="[a-zA-Z0-9\s]+" required>
  </div>
  <ul class="alert-error" *ngIf="name.touched && name.errors">
    <li *ngIf="name.errors.required"> Name is required. </li>
    <li *ngIf="name.errors.pattern">Invalid name.</li>
  </ul>
</div>

Currently error messages are showing up, but I want to change the textbox border-color to red. How to do that.

like image 431
Nagarjuna Reddy Avatar asked Sep 29 '16 07:09

Nagarjuna Reddy


2 Answers

Here is another solution.

input.ng-invalid.ng-touched {
  border: 1px solid red;
}

If you inspect your input field, you can see some css classes that Angular dynamically attach to your element that you can take advantage of.

like image 125
Andreas Chatzivasileiadis Avatar answered Sep 20 '22 19:09

Andreas Chatzivasileiadis


You can use ngClass directive to add css class to your input field when it is invalid:

<input #name="ngModel" id="name" name="name" type="text" class="form-control text-line"
[ngClass]="{'red-border-class': name.errors}" [(ngModel)]="PersonInfo.name" pattern="[a-zA-Z0-9\s]+" required>

Hope you don't need help writing css. :-)

like image 37
Stefan Svrkota Avatar answered Sep 19 '22 19:09

Stefan Svrkota