Angular 4/5 Validator class error display on form

In last article i discussion on the how to add validation add in the form. Now in this article I discussion on how to display that error on the form. In last article we discussion on how to add the validation on FormBuilder it display like code below.

ngOnInit() {

  this.signupfrm = this.formBuilder.group({
      name: new FormControl('', [Validators.required,Validators.minLength(4)]),
      email:new FormControl('', [Validators.required,Validators.email]),
      pwd: new FormControl('', [Validators.required,Validators.minLength(5)]),
      country: new FormControl('', Validators.required)
    });

    this.country = [
                      {'name':'India','value':'india'},
                      {'name':'United State','value':'us'},
    ];
        
  }



To display error message we need to create component for displaying error on each field. let’s create one component called “ControlMessagesComponent” in components/validation folder. Attached screen-shot for structure display below.

In that component we need to get value form the form field so we need to import

import { Input } from '@angular/core';

using this you can get value form where we pass the value of it. I have added code on that component doisplay as below.

import { Component, Input } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { ValidationService } from '../../services/validation.service';
@Component({
  selector: 'control-messages',
  template: `<div *ngIf="errorMessage !== null">{{errorMessage}}</div>`
})
export class ControlMessagesComponent {
 // errorMessage: string;
  @Input() control: FormControl;
  constructor() { }

  get errorMessage() {
    for (let propertyName in this.control.errors) {
      if (this.control.errors.hasOwnProperty(propertyName) && this.control.touched) {
        return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
      }
    }
    
    return null;
  }
}

  



We need to create here “ValidationService” in services folder and imported in the control message. On that service we have one method to return validation filed accordingly return message. Code of “ValidationService”

export class ValidationService {
    static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
        let config = {
            'required': 'Required',
            'minlength': `Minimum length ${validatorValue.requiredLength}`,
            'email': 'Invalid email address',
        };
        return config[validatorName];
    }
}

In “ValidationService” created one static method called “getValidatorErrorMessage” with 2 argument validator name & validator value.

Must need entry for “ControlMessagesComponent” component entry in “app.module.ts”.
After in HTML we need to add code display like below.

<form [formGroup]="signupfrm" >
<input type="text" name="name" formControlName="name" class="form-control"> 
<control-messages [control]="signupfrm.controls.name" class="error-msg messages text-left text-danger"></control-messages>
</form>

These simple steps you can add message display error below filed. Display output demo display like below.

Any question regarding displaying error please comment below. i can solve your issue.

Spread the love
  • 25
  •  
  •  
  •  
  •  
  •  
  •  
  •