Skip to content Skip to sidebar Skip to footer

Form Validation Is Not Working In Angular?

I want to check whether the dropdown is empty. Need to show the required message and If not empty, enable the submit button. If empty, disable the submit button. Below is my html

Solution 1:

You are currently assigning formcontrols to your formcontrol, whereas you want to assign value to your form controls. Below you are assigning form control name to formcontrol name:

WRONG:

name = new FormControl('', Validators.required);

this.myForm = this.formBuilder.group({
  'name': [this.name, Validators.required],
  // ...
});

so instead, just declare name, do what you want with the value, then assign that value to your form control...

CORRECT:

name: string;

this.myForm = this.formBuilder.group({
  'name': [this.name, Validators.required],
  // ...
});

Then just add [disabled]="!myForm.valid" on your submit button.

As for the other question, by default Angular material doesn't show error message unless the field has been touched, so you need to have a custom error state matcher that shows the error even when field is not touched (if that is what you want):

import {ErrorStateMatcher} from'@angular/material/core';

exportclassMyErrorStateMatcherimplementsErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control.invalid);
  }
}

and in your TS, declare a error state matcher:

matcher = new MyErrorStateMatcher();

and use in template:

<mat-select formControlName="name" ... [errorStateMatcher]="matcher">

Here's your

StackBlitz

Solution 2:

To make the submit button disabled (link)

<button type="submit" [disabled]="!myForm.valid" mat-button cdkFocusInitial>Add</button>

In order to check whether the dropdown is empty or not, you need to make the form fields required like

this.myForm = this.formBuilder.group({
  'name': [this.name, Validators.required],
  'symbol': [this.symbol, [Validators.required]]
});

Inorder to show the error highlight you need to add an ngClass in the templete like.

[ngClass]="{'error': myForm.controls.name.valid == false}"

Solution 3:

You have to insert the validator into the form builder object.

Have a quick look at:

https://angular.io/guide/reactive-forms#validatorsrequired

this.heroForm = this.fb.group({
  name: ['', [Validators.required] ],
});

As for the button:

<button type="submit" [disabled]="!form.valid"  mat-button cdkFocusInitial>Add</button>

Post a Comment for "Form Validation Is Not Working In Angular?"