<mat-form-field class="input-label-add">
<input matInput placeholder="Registration **" formControlName="registration">
<mat-error *ngIf="addLockerForm.get('registration').hasError('maxlength')">registration cannot exceed 8 characters</mat-error>
<mat-error *ngIf="addLockerForm.get('registration').errors">registration or surname is required</mat-error>
</mat-form-field>
this.addLockerForm = this.formBuilder.group({
locker_serial_number: [null, Validators.required],
customer_surname: [null],
registration: [null, Validators.maxLength(10)],
mobile: [null],
email: [null],
date_in: [null, Validators.required],
date_out: [null, Validators.required],
},
{ validator: [this.validateCustomerDetails, this.validateCustomerContact] });
addLockerForm.get('registration').hasError('maxlength') 始终为 false
最佳答案
你能试试这个吗?
addLockerForm.get('registration').errors.maxlength
https://angular.io/guide/form-validation#validator-functions
编辑 1
你不需要使用.errors
。
请像这样更新您的代码:
<mat-form-field class="input-label-add">
<input matInput placeholder="Registration **" formControlName="registration">
<mat-error *ngIf="addLockerForm.get('registration').hasError('maxlength')">registration cannot exceed 8 characters</mat-error>
<mat-error *ngIf="addLockerForm.get('registration').hasError('required')">registration or surname is required</mat-error>
</mat-form-field>
registration: [null, [Validators.required, Validators.maxLength(8)]],
关于Angular 8 - 表单验证无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59627527/