Angular validation message for maxlength attribute

37,630

Solution 1

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

Solution 2

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

Share:
37,630
Mathis Garberg
Author by

Mathis Garberg

My name is Mathis Garberg, I am 24 years old and from Notodden in Telemark.I have a bachelor in web development at NTNU i Gjøvik. Throughout my education, I've gained experience in several media related subjects and a broad technical expertise in multiple web technologies. Among the technologies I have skills in are web technologies like HTML, CSS and JavaScript. I've also worked a lot with PHP and C# and popular web frameworks like React, Vue 2, AngularJS and Angular v.x. In the summer of 2017, I spent my summer developing an application for Gjøvik kommune called "Byvandring i Gjøvik", using the Ionic framework with Firebase. As a person, I'm goal-oriented, hard working and forthcoming. I am curious about new technologies and a quick learner. I like to work in teams and I am open for new challenges. In my free time, I like to work out, watch programming vids, play video games, go out and have fun and play sports. And, of course I love coffee &lt;3

Updated on July 05, 2022

Comments

  • Mathis Garberg
    Mathis Garberg almost 2 years

    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.

  • Mathis Garberg
    Mathis Garberg over 6 years
    Quick and easy fix. Love it.
  • Koja
    Koja over 4 years
    This answer doesn't allow the user to enter more characters, so it doesn't solve the original problem.
  • Koja
    Koja over 4 years
    I wanted to allow the user to type in more characters than the maximum validation length, and react on that (disable submit and show an error). Mohamed's answer below helped me achieve that.
  • Vega
    Vega over 4 years
    @Koja 1. if you remove mxLength, you will be able to achieve it 2. The Question expressly uses ngModel and not reactive forms! So my answer is more appropriate
  • Koja
    Koja over 4 years
    You are right, it does work. But if you want to show an error message and disable submit when .length > 10 , you need to write that rule two times in the template for each input that you wish to validate.
  • Vega
    Vega over 4 years
    @Koja, My answer is for a specific setup, no form is involved. If you need validation for the form, of course reactive forms provide every tool, I say go for it. The OP had no reactive form but had ngModel, I provided an answer that solved the situation and they accepted this answer