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 .

Zhu
  • 3,679
  • 14
  • 45
  • 76

3 Answers3

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.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • 1
    It's showing only the FirstName is required validation. other messages are not working. @SiddAjmera – Zhu Sep 19 '18 at 05:48
  • Updated the answer. There was an issue with the case of error names. `minLength` should have been `minlength` – SiddAjmera Sep 19 '18 at 05:50
  • 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 – Zhu Sep 19 '18 at 05:55
  • 1
    You might want to change the sequence of error messages. I think there's a priority sequence. I'm not sure though. – SiddAjmera Sep 19 '18 at 05:56
  • Sidd, is right. @Zhu. Just change the order your ts. file – Patricio Vargas Sep 19 '18 at 05:58
  • can you please help me to solve this https://stackoverflow.com/questions/52417652/how-to-validate-input-fields-one-by-one-in-angular-6?noredirect=1#comment91778499_52417652 @SiddAjmera – Zhu Sep 20 '18 at 05:05
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;
  }
}
Krishna Rathore
  • 9,389
  • 5
  • 24
  • 48
  • 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 – Zhu Sep 19 '18 at 05:58
  • add this condition
    minimum 4 char required
    – Krishna Rathore Sep 19 '18 at 06:01
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>
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100