Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular validation message for maxlength attribute

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.

like image 741
Mathis Garberg Avatar asked Oct 10 '17 13:10

Mathis Garberg


2 Answers

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

like image 113
Mohamed Ali RACHID Avatar answered Sep 19 '22 12:09

Mohamed Ali RACHID


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

like image 26
Vega Avatar answered Sep 19 '22 12:09

Vega