DEV Community

Ushmi Dave
Ushmi Dave

Posted on

Best way to show error messages in angular reactive forms

When multiple validations are involved in a single formControl, we need to put multiple *ngIf in the HTML and bind the respective validator's error messages which makes the code clumsy.

Here, we will discuss the approach of showing error message in a better and simplified way.

We build a userInfo form where the user can enter details like username and password, username contains one required validators and password contains required and password validation we shall show error messages without using *ngIf conditions, I will use password validation of @rxweb/reactive-form-validators validation framework. This validation framework provides more than 50+ validators with cross-field validation.

Let’s install first @rxweb/reactive-form-validators.

npm install @rxweb/reactive-form-validators

Now, Register the ‘RxReactiveFormsModule’ in the root module.

  import { NgModule } from '@angular/core';
  import { BrowserModule } from '@angular/platform-browser';
  import { FormsModule,ReactiveFormsModule } from '@angular/forms';

  import { AppComponent } from './app.component';

  import {  RxReactiveFormsModule } from "@rxweb/reactive-form-validators"
  @NgModule({
  imports:      [ BrowserModule, 
  FormsModule,ReactiveFormsModule,RxReactiveFormsModule ],
  declarations: [AppComponent],
  bootstrap:    [ AppComponent]
  })
  export class AppModule { }
Enter fullscreen mode Exit fullscreen mode

Now, we create userInfo formGroup having the respective formControls and bind errorMessage on formControls having single or multiple validators.

Single error Message

First we will create user component and group a single formControl into userInfo formGroup.

  import { Component, OnInit } from '@angular/core';
  import { FormGroup, FormBuilder, } from "@angular/forms"
  import { RxwebValidators,RxFormBuilder} from '@rxweb/reactive-form-validators';

  @Component({
    selector: 'app-user',
    templateUrl: './user.component.html'
  })
  export class UserComponent implements OnInit {
    userFormGroup: FormGroup

    constructor(
        private formBuilder: RxFormBuilder )
    { }

    ngOnInit() {
        this.userFormGroup = this.formBuilder.group({
            userName:['', RxwebValidators.required()]
        });

    }
  }
Enter fullscreen mode Exit fullscreen mode

Now we will bind the errorMessage property on the formControl in the html.

<div>
    <form  [formGroup]="userFormGroup">
      <div class="form-group">
        <label>UserName</label>
        <input type="text" formControlName="userName" class="form-control"  />
       <small class="form-text text-danger">{{userFormGroup.controls.userName.errorMessage}}<br/></small>   
      </div>
      <button [disabled]="!userFormGroup.valid" class="btn btn-primary">Submit</button>
    </form>
  </div>
Enter fullscreen mode Exit fullscreen mode

Please refer the working Example

Multiple error Messages

We will create formControl of password in the same formGroup in the component

  import { Component, OnInit } from '@angular/core';
  import { FormGroup, FormBuilder, } from "@angular/forms"
  import { RxwebValidators,RxFormBuilder} from '@rxweb/reactive-form-validators';

  @Component({
    selector: 'app-user',
    templateUrl: './user.component.html'
  })
  export class UserComponent implements OnInit {
    userFormGroup: FormGroup

    constructor(
        private formBuilder: RxFormBuilder )
    { }

    ngOnInit() {
        this.userFormGroup = this.formBuilder.group({ 
              password : ['', 
  [RxwebValidators.required(),RxwebValidators.password({ validation: { maxLength: 
  10, minLength: 5, digit: true, specialCharacter: true } })]],
        });

    }
  }
Enter fullscreen mode Exit fullscreen mode

Now we will bind the errorMessages property on the formControl in the html and display them using *ngFor.

<div>
  <form  [formGroup]="userFormGroup">
        <div class="form-group">
      <label>Password</label>
      <input type="text" formControlName="password" class="form-control"  />
     <small class="form-text text-danger" *ngFor="let errorMessage of userFormGroup.controls.password['errorMessages']">
       {{errorMessage}}<br/>
     </small>
    </div>

    <button [disabled]="!userFormGroup.valid" class="btn btn-primary">Submit</button>
  </form>
</div>
Enter fullscreen mode Exit fullscreen mode

Please refer the working example

If you have any question/suggestion, Please share your comments below.

Top comments (0)