htmlcssangularangular2-form-validation

Angular form validation - display error in another row/div


The current error message displays just below the text box. But I want to display it in the entire row below to the label and text box

I tried it by moving the div like below, but it doesn't work. I see the css for invalid-feedback is still display: none. It should change to display: block or remove

<div class="form-group">
  <div class="row">
  <div class="col-sm">
    <label>First Name</label>
  </div>
  <div class="col-sm">
    <input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
  </div>
  </div>
  <div class="row">
  <div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
    <div *ngIf="f.firstName.errors.required">First Name is required</div>
  </div>
  </div>
</div>
<div class="form-group">
  <div class="row">
  <div class="col-sm">
    <label>First Name</label>
  </div>
  <div class="col-sm">
    <input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
  </div>
  </div>
  <div class="row">
  <div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
    <div *ngIf="f.firstName.errors.required">First Name is required</div>
  </div>
  </div>
</div>

If I make the code change as above, I don't get the error message, but I still get the border of the text box red.

Expect: The error message should display like below as shown in the picture

https://stackblitz.com/edit/angular-7-reactive-form-validation-jhuxvm

enter image description here


Solution

  • If you want the form validation errors to display underneath each of the labels as well. Simply add the error containers <div class="invalid-feedback"> underneath each of the form labels and give them each a style of display: block as they won't show until the other form errors underneath the <input>'s are displayed as well.

    Have a look at this StackBlitz Demo. View the full page here.

    Form with validation errors under labels as well