Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reserve space for form validation messages in Angular?

This question has a Stackblitz based on the Angular documentation, Validating input in reactive forms. Given a simple Angular form with validation:

enter image description here

How can I stop the form from jumping around when displaying error messages?

For example, upon entering an invalid email address, the password field is pushed down to make way for the error message. In the same way the login button is pushed down when the password validation fails.

enter image description here

I have previously used Angular Material Form Fields which has its own way of reserving space for validation messages.

I understand that I need to reserve some space for the error message, but how should this be achieved? Two ideas I've rejected so far:

  • Hard coding the height of a space in which to show error messages (what if the user is using a different font size or some other setting? Seems too fragile.)
  • Using a white font on a white background to reserve space when there is no error message (breaks screen readers, feels hacking)

The HTML code for conditionally displaying error messages is

<form [formGroup]="form" fxLayout="column" fxLayoutGap="24px">

    <!-- Email -->
    <div>
        <label for="email">Email</label>
        <input id="email" formControlName="email">
        <!-- Errors -->
        <div *ngIf="email.invalid && email.dirty" class="warn">
            <div *ngIf="email.errors.required">Email is required</div>
            <div *ngIf="email.errors.email">Must be a valid email address</div>
        </div>
    </div>

    <!-- Password -->
    <div>
        <label for="password">Password</label>
        <input id="password" type="password" formControlName="password">
        <!-- Errors -->
        <div *ngIf="password.invalid && password.dirty" class="warn">
            <div *ngIf="password.errors.required">Password is required</div>
        </div>
    </div>

    <!-- Button -->
    <button class="submit">Login</button>

</form>
like image 952
Jack Avatar asked Aug 31 '25 15:08

Jack


1 Answers

One way to deal with this is to make the div wrapping the errors have a height so it is always on the screen and the error messages inside it appear conditionally.

<div class="warn">
    <ng-container *ngIf="email.invalid && email.dirty">
            <div *ngIf="email.errors.required">Email is required</div>
            <div *ngIf="email.errors.email">Must be a valid email address</div>
    </ng-container>
</div> 

.warn {
  color: #FF3636;
  font-size: 14px;
  text-align: right;
  height: 16px;
}

Now the warn div is on the page, taking up 16px and just waiting to contain a message should validation fail.

like image 72
Steve Avatar answered Sep 02 '25 04:09

Steve