Topic: Outline inputs - Material 2.0 Reactive Form Validation to modify border colors

rtchrisdev pro asked 5 years ago


Expected behavior

It is possible to change the border color for Outline inputs - Material 2.0 based on Reactive Form Validators.. The example on the website is template driven using [(ngModel)] . I would like to use Reactive Form Validation with CSS to change the border outline. e.g. green or blue border for valid, and a red border for invalid. I use the CSS code below to mark in input box (non-MDB) green or red.

input.ng-invalid {border-left: 5px solid red} input.ng-valid {border-left: 5px solid green}

Actual behavior

*Resources (screenshots, code snippets etc.)


Damian Gemza staff commented 5 years ago

You should definitely try the @eMD Technologies approach, @rtchrisdev.


eMD Technologies free answered 5 years ago


Hi Rtchrisdev,

I have done something similar to what you are trying to achieve.

component.html:

<input type="text" class="form-control" [ngClass]="{'border-danger': (submitted && f.namefield.errors?.required)}"
  id="namefield" formControlName="namefield">

component.ts:

// field to indicate form submission state
  submitted: boolean;

  // getter to make accessing controls on html easier
  get f() { return this.stockForm.controls; }

  onSubmit(): void {
    // indicate that form was submitted
    this.submitted = true;

    // if form is still invalid then ignore
    if (!this.stockForm.valid) {
      return;
    }

    // form is now in a valid state, so proceed with what it is you want to do with the value    
  }

Explanation: [ngClass] allows you to specify the border style class based on the result of the expression. Once the form is submitted, we set the submitted property, then in the HTML we check if the form was submitted and if there are any errors on that specific formControl field. If both of these are true, the 'border-danger' class will apply and we will end up with a red outline around our input field.



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Pro
  • Premium support: No
  • Technology: MDB Angular
  • MDB Version: 7.5.4
  • Device: MAC
  • Browser: Chrome
  • OS: Mojave 10.14.5
  • Provided sample code: No
  • Provided link: No