How to display different error messages based on user input in Angular 6

Viewed 16135

I am new to angular 6 ,Here I want to validate a user input field and display different error messages based on the given input.

In my project I am using Angular Material design for UI.

What I want to do is

  • If the user click on the save button display a error message as "Please enter your FName".
  • If user touched but not enter anything and clicked on save button display a error message as "Please enter your FName".
  • If user started to enter char it should show a error message as "minimum 4 char required"
  • Once the user reached 15 char it should show a error message as "Maximum 20 char only"
  • If the user enter any special char and space and other input an error message as "Enter only alphabets"

Now it changes to RED color when the input does not meet the successful validation.but I want to display an error message for each validation in the formControl.

Here I have a mat-input-field.

<form [formGroup]="userAddressValidations" novalidate>
    <mat-form-field appearance="outline" class="col-sm-6">
        <mat-label>First Name</mat-label>
        <input matInput formControlName="firstName">
    </mat-form-field>
</form>

<button mat-raised-button class="continueBtnHeight" color="warn">
<span>Save</span>
</button>

Ts file

export class ButtonToggleOverviewExample {
  userAddressValidations: FormGroup;
  constructor(private formBuilder: FormBuilder) { }
  ngOnInit() {
    this.userAddressValidations = this.formBuilder.group({
      firstName: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(20), Validators.pattern('[a-zA-Z]+')]]
    });

  }
}

stackblitz:https://stackblitz.com/edit/angular-t1k1x6-skowwq?file=app%2Fbutton-toggle-overview-example.ts

can anyone help me to solve this .

3 Answers

Try this:

<form class="example-form" [formGroup]="userAddressValidations">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="First Name" formControlName="firstName">
    <mat-error *ngIf="userAddressValidations.get('firstName').hasError('required')">
      First Name is Required!
    </mat-error>
    <mat-error *ngIf="userAddressValidations.get('firstName').hasError('minlength')">
      First Name should be atleast 4 characters long!
    </mat-error>

    <mat-error *ngIf="userAddressValidations.get('firstName').hasError('maxlength')">
      First Name can be atmax n characters long!
    </mat-error>

    <mat-error *ngIf="userAddressValidations.get('firstName').hasError('pattern')">
      First Name must follow this pattern!
    </mat-error>
  </mat-form-field>

</form>

Here's a Sample StackBlitz for your ref.

use hasError('invalidName') for if the user enter any special char and space

Stackblitz

Component.html

<form [formGroup]="userAddressValidations">

    <label>User Name : 
        <input type="text"  formControlName="firstName">
    </label><br>

    <div class="errors" *ngIf="userAddressValidations.get('firstName').invalid && (userAddressValidations.get('firstName').touched || userAddressValidations.get('firstName').dirty)">

        <div *ngIf="userAddressValidations.get('firstName').hasError('required')">
            Please enter your FName
        </div>

        <div *ngIf="userAddressValidations.get('firstName').errors.minlength">
            minimum 4 char required
        </div>

        <div *ngIf="userAddressValidations.get('firstName').errors.maxlength">
            Maximum 20 char only
        </div>

        <div class="error-text" *ngIf="userAddressValidations.get('firstName').hasError('invalidName')">
            Enter only alphabets
        </div>
    </div>

</form>

Component.ts

this.userAddressValidations = fb.group({
      firstName: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(20), usernameValidator]]
});

username.validators.ts

import { AbstractControl, ValidationErrors } from "@angular/forms"

export const usernameValidator = function (control: AbstractControl): ValidationErrors | null {

  let value: string = control.value || '';

  if (value) {
    const matches = value.match(/^[a-zA-Z]+$/);
    return matches ? null : { 'invalidName': true };
  } else {
    return null;
  }
}

Take a look this tutorial https://codecraft.tv/courses/angular/forms/model-driven-validation, You can also reference to this stackoverflow question: Display custom validator error with mat-error

But here's a small example:

<form [formGroup]="userAddressValidations" novalidate>
    <mat-form-field appearance="outline" class="col-sm-6">
        <mat-label>First Name</mat-label>
        <input matInput formControlName="firstName">
         <mat-error *ngIf="email.errors.required">{{getErrorMessage()}}</mat-error>
         <mat-error *ngIf="email.errors.minlength">{{getErrorMessage()}}</mat-error>
    </mat-form-field>
</form>
Related