Reactive Forms validation: minlength instead of minLength

I stumbled upon a silly gotcha moment while implementing validation in an Angular form recently.

Using Reactive Forms, I created a form with basic controls. Among them, a simple textbox for a name field. I used the FormBuilder to define the form’s fields and their associated validation configuration, as you do.

For the name field, I added three validators namely: required, minLength and maxLength.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular';
  deviceForm: FormGroup;
  constructor(private fb: FormBuilder) {

  }

  ngOnInit() {
    this.deviceForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]]
    });
  }
}

The corresponding template file looks like this:

<form novalidate [formGroup]="deviceForm">
  <input type="text" formControlName="name" />
  <div *ngIf="deviceForm.get('name').invalid && (deviceForm.get('name').touched || deviceForm.get('name').dirty)">
    <span *ngIf="deviceForm.get('name').errors?.required">
      The name is required.
    </span>
    <span *ngIf="deviceForm.get('name').errors?.minLength">
      The name must be at least three characters long.
    </span>
    <span *ngIf="deviceForm.get('name').errors?.maxLength">
      The name cannot exceed 50 characters.
    </span>
  </div>
</form>

The expected outcome is that when the user “touches” the text field and leaves it without typing anything, the required validation would be triggered.

It works!

When the user types in two characters only, the minLength validator would be triggered… except it did not.

Nothing?!?!?

Interesting.

via GIPHY

After digging for a little bit, I found out that the culprit is because the validation error key for the minLength validator is “minlength“. All small letters!

<span *ngIf="deviceForm.get('name').errors?.minLength">
    The name must be at least three characters long.
</span>

A subtle but very important difference. One would think that the validation error key would be the same to how it is defined (Validator.minLength). Alas, it is not.

After updating the validation specification in the template file like so:

<span *ngIf="deviceForm.get('name').errors?.minlength">
    The name must be at least three characters long.
</span>

The minLength validator is now triggered and the correct error message is displayed.

Gotcha indeed!

Hope you found this useful. Happy coding!

Cover photo by Mimi Thian on Unsplash

%d bloggers like this: