Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular form validation working only after focus change

I have a angular form on which I want to do some validation. Now, when the textarea is loaded for the first time and I type something violating the validation, it does not show me error.

When I change focus to some other element, then the error is shown.

But, after that whenever there is a violation, the error is shown immediately whithout focus change required.

<form [formGroup]="AddEditform" novalidate autocomplete="off">
    <mat-form-field appearance="outline">
        <textarea matInput name="user" formControlName="users" id="user">
        </textarea>
        <mat-error
            *ngIf="!AddEditform.valid && AddEditform.get('users').hasError('maxlength')"
        >
            Exceeded maximum length
        </mat-error>
    </<mat-form-field>
</form>


AddEditform: FormGroup;

constructor(
  private fb: FormBuilder,
) { }

ngOnInit() {

  this.AddEditform = this.fb.group({
    users: [
      '',
      [
        Validators.maxLength(100)
      ],
    ],
  });
}

Why is this behavior happening? Why on the first time itself, the validation is not happening without focus change required?

like image 621
user5155835 Avatar asked Jun 19 '26 05:06

user5155835


1 Answers

Solution of same found in StackBlitz Link

Error is in your <mat-error>, is not firing when input value change validation is occurs. for solution of that you have to user custom ErrorStateMatcher in your class.ts file and you need to tell in template that you need custom ErrorStateMatcher.

component.html

<form  novalidate autocomplete="off">
     <mat-form-field appearance="outline">
         <textarea matInput #inputValue name="user" 
              [formControl]="users" id="user" [errorStateMatcher]="matcher" >
         </textarea>
       <mat-error>
         Exceeded maximum length
       </mat-error>
    </mat-form-field>
</form> 

component.ts

export class AppComponent  {
    name = 'Angular';
    AddEditform: FormGroup;
    users = new FormControl('', [Validators.maxLength(5)]);
    matcher = new MyErrorStateMatcher();

    ngOnInit(){ }
}

export class MyErrorStateMatcher implements ErrorStateMatcher {
       isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
            const isSubmitted = form && form.submitted;
            return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
        }
}
like image 148
GaurangDhorda Avatar answered Jun 21 '26 22:06

GaurangDhorda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!