1

I am working on an application where I am implementing max length but it is not working. below is my implementation

TS

 this.customPaymentForm = new FormGroup({ amount: new FormControl(0, [Validators.required, Validators.pattern(/^\d{1,4}(\.\d{1,2})?$/)]), cVVCode: new FormControl('', [Validators.required,Validators.maxLength(4)), }) 

HTML

<div class="input"> <label for="">Cryptogramme visuel <span class="req">*</span></label> <input type="number" class="form-control" formControlName="cVVCode" placeholder="XXXX" /> <div class="text-error" *ngIf="customPaymentForm.get('cVVCode').errors && (customPaymentForm.get('cVVCode').touched || customPaymentForm.get('cVVCode').dirty)"> <div *ngIf="customPaymentForm.get('cVVCode').hasError('required')">Cryptogramme visuel est requis.</div> <div *ngIf="customPaymentForm.get('cVVCode').hasError('maxlength')">Cryptogramme visuel doit avoir au maximum 4 caractères.</div> </div> </div> 

It doesn't show an error message.

1
  • Please provide a stackblitz repro, this should work. Commented Jun 5, 2024 at 9:27

1 Answer 1

1

Since the input field is of type number, you should use max validator, which checks the maximum possible number of 4 characters (9999).

import { CommonModule } from '@angular/common'; import { Component } from '@angular/core'; import { ReactiveFormsModule, FormGroup, FormControl, Validators, } from '@angular/forms'; import { bootstrapApplication } from '@angular/platform-browser'; import 'zone.js'; @Component({ selector: 'app-root', standalone: true, imports: [ReactiveFormsModule, CommonModule], template: ` <form [formGroup]="customPaymentForm"> <div class="input"> <label for="">Cryptogramme visuel <span class="req">*</span></label> <input type="number" class="form-control" formControlName="cVVCode" placeholder="XXXX" /> {{customPaymentForm.get('cVVCode')?.errors | json}} | <div class="text-error" *ngIf="customPaymentForm.get('cVVCode')?.errors && (customPaymentForm.get('cVVCode')?.touched || customPaymentForm.get('cVVCode')?.dirty)"> <div *ngIf="customPaymentForm.get('cVVCode')?.hasError('required')">Cryptogramme visuel est requis.</div> <div *ngIf="customPaymentForm.get('cVVCode')?.hasError('max')">Cryptogramme visuel doit avoir au maximum 4 caractères.</div> </div> </div> </form> `, }) export class App { name = 'Angular'; customPaymentForm = new FormGroup<any>({}); ngOnInit() { this.customPaymentForm = new FormGroup<any>({ amount: new FormControl(0, [ Validators.required, Validators.pattern(/^\d{1,4}(\.\d{1,2})?$/), ]), cVVCode: new FormControl('', [ Validators.required, Validators.max(9999), ]), }); } } bootstrapApplication(App); 

Stackblitz Demo

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.