Angular validation message for maxlength attribute

Mathis Garberg picture Mathis Garberg · Oct 10, 2017 · Viewed 30.5k times · Source

I'm having some trouble with displaying error messages for the maxlength attribute in Angular.

Problem

Since the maxlength attribute don't allow more characters than the specified amount, I'm having trouble displaying my error message. Is there any way to turn of the default behavior (allow the user to type more characters), in order to display my error message.

Code for textarea

<textarea maxlength="10"
          [(ngModel)]="title.value"
          #title="ngModel"></textarea>

Code for Angular validation

<div *ngIf="title.errors && (title.dirty || title.touched)"
      class="alert alert-danger">
    <div [hidden]="!title.errors.maxlength">
      Only 10 characters allowed.
  </div>
</div>

If you want me to provide any additional information, please let me know.

Answer

Mohamed Ali RACHID picture Mohamed Ali RACHID · Oct 10, 2017

you can work with Reactive forms to validate properly your form, here is a simple example how to use reactive forms :

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

@Component({
  selector: 'title-form',
  template: `
    <form novalidate [formGroup]="myForm">
      <label>
        <span>Full title</span>
        <input type="text" placeholder="title.." formControlName="title">
      </label>
      <div*ngIf="myForm.controls['title'].touched && myForm.get('title').hasError('required')">
        Name is required
      </div>
      <div *ngIf="myForm.controls['title'].touched && myForm.controls['title'].hasError('maxlength')">
        Maximum of 10 characters
      </div>
    </form>
  `
})
export class TitleFormComponent implements OnInit {
  myForm: FormGroup;
  constructor(private fb: FormBuilder) {}
  ngOnInit() {
    this.myForm = this.fb.group({
      title: ['', [Validators.required, Validators.maxLength(10)]],
    });
  }

}

hope it helps u :)