Nagarjuna Reddy
Nagarjuna Reddy

Reputation: 4195

Angular2: change border color for error in form validation

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.

Upvotes: 17

Views: 53576

Answers (4)

Raja Ram T
Raja Ram T

Reputation: 9071

We can achieve different ways, but I personally preferred the following way.

HTML

<form [ngClass]="{ 'form-submit': isSubmit}" (ngSubmit)="onSubmit()" name="forgotPasswordForm" [formGroup]="forgotPasswordForm">                
  <input name="email" type="email" class="form-control" id="email" placeholder="Email" formControlName="email">
  <div class="invalid-feedback form-error" *ngIf="...">
    .......
  </div>  
 </form>

CSS:

.form-group input.ng-invalid.ng-touched, 
.form-group input.ng-invalid:focus, 
.form-group select.ng-invalid.ng-touched, 
.form-group textarea.ng-invalid.ng-touched,
.form-submit input.ng-invalid,
.form-submit select.ng-invalid,
.form-submit  textarea.ng-invalid
{
    border-color: #ff4c6a;
}

.invalid-feedback.form-error {
    display: block;
}

Upvotes: 0

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.

Upvotes: 28

micronyks
micronyks

Reputation: 55443

Just find .alert-error class in css file and add border property.

.alert-error{
   ...
   border:1px solid red;
   color:red;
}

Upvotes: 1

Stefan Svrkota
Stefan Svrkota

Reputation: 50623

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. :-)

Upvotes: 15

Related Questions