Home > Blockchain >  Angular form validation fails after removing `is-invalid` class from input field
Angular form validation fails after removing `is-invalid` class from input field

Time:07-14

I have prepared on StackBlitz (https://stackblitz.com/edit/angular-ivy-iuif7k?file=src/app/app.component.ts) a very simple app with form containing one input field and one submit button. The code contains classic validation for the required username field in validation-form.component.html. The input field contains the dynamic class initialization [ngClass]="{ 'is-invalid': submitted && f['username'].errors }". Validation (after pressing Submit button) is working fine (displaying Username is required - when input field is left empty) until I remove from input field the above class [ngClass]="{ 'is-invalid': submitted && f['username'].errors }". After removing that class, validation does not display an error anymore when I press submit button. Is this by design or it is a genuine bug in Angular?

CodePudding user response:

The error element is there even when you remove ngClass, It just doesn't display because the default class you have .invalid-feedback has display: none

Remove .invalid-feedback class and you will see it working with or without ngClass

It works with ngClass because when you submit without entering the value ngClass gets satisfied and is-invalid class gets added, and this class has display:block which overrides display:none

CodePudding user response:

This has nothing to do with Angular. is-invalid is a Bootstrap CSS class in which you control by adding it to a particular element using a condition; in your case the condition is submitted && f['username'].errors.

This is-invalid is usually used to wrap the error message using *ngIf and also have the CSS error attributes such as the red border color on input etc...

So when you remove it, the styling won't be visible.

Proper "Angular" validation is required within the onSubmit method like this

onSubmit(value: any) {
  this.submitted = true;
  if (!this.myForm.valid) {
    return;
  }
}
  • Related