Angular validation message for maxlength attribute

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 :)


You can achieve it by setting the condition directly on the length of the input. A span tag with *ngIf can show/hide the error message:

HTML

<textarea class="form-control" id="title"  
type="number" name="title" [(ngModel)]="titleModel"></textarea> 
<span style="color:red" *ngIf="titleModel?.length > 10">
      10 max
</span>

Class: ...

  titleModel = 'I have more than 10 characters'

... DEMO