Display suitable validation error message

247 Views Asked by At

HTML

<form class="row" [formGroup] = "loginForm" (ngSubmit)="UpdateProfile()">
    <input type="text" formControlName="first_name" />
    <span 
        *ngIf="this.loginForm.controls.first_name != null 
                && this.loginForm.controls.first_name.errors != null">
        Please enter first name
    </span>
            
    <button type="submit" [disabled]="loginForm.invalid" class="btn btn-primary">
        Update Profile
    </button>
</form>

Js Side

this.loginForm = new FormGroup({
    first_name: new FormControl(this.userObj.first_name, [
        Validators.required, 
        Validators.minLength(3), 
        Validators.maxLength(20)
    ])
});

Issue details

Is there any way to identify which kind of validation was imposed. Like was it required or min length or max length for displaying appropriate message

1

There are 1 best solutions below

1
On

The errors field under a control will have the relevant error message. You can see error object for better understanding. Add below block in this form component to view the error:

{{ loginForm.controls.first_name.errors | json }}  

You will notice that the error object changes as you start typing in the input block, in beginning it's

{ "required": true }

Then it chnages to min lin validation error:

{ "minlength": { "requiredLength": 3, "actualLength": 2 } }

Then it will change to max len validation error:

{ "maxlength": { "requiredLength": 20, "actualLength": 25 } }

So you can display different error messages based on these error details. See below:

  <span *ngIf="loginForm.controls.first_name.errors">
    <span *ngIf="loginForm.controls.first_name.errors?.required">
      Please enter first name
    </span>
    <span *ngIf="loginForm.controls.first_name.errors.minlength">
        First name must have at least 3 characters
    </span>
    <span *ngIf="loginForm.controls.first_name.errors.maxlength">
        First name must not be more than 20 characters
    </span>
  </span>