我正在开发一个应用程序,我正在实现最大长度,但它不起作用。下面是我的实现
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>
它不显示错误消息。
由于输入字段的类型为
number
,因此您应该使用 max
验证器,它检查 4 个字符的最大可能数量 (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);