4

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 .

1
  • Use mat-error Commented Sep 19, 2018 at 5:39

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

It's showing only the FirstName is required validation. other messages are not working. @SiddAjmera
Updated the answer. There was an issue with the case of error names. minLength should have been minlength
Here If the user starts with special character error message should be as the "First Name must follow this pattern!" instead of minimum char error. If I am right how to do it brother @SiddAjmera
You might want to change the sequence of error messages. I think there's a priority sequence. I'm not sure though.
Sidd, is right. @Zhu. Just change the order your ts. file
|
1

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;
  }
}

2 Comments

Here If the user starts with special character error message should be as the "First Name must follow this pattern!" instead of minimum char error. If I am right how to do it brother @Krishna Rathore
add this condition <div *ngIf="!userAddressValidations.get('firstName').hasError('invalidName') && userAddressValidations.get('firstName').errors.minlength"> minimum 4 char required </div>
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.