<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のままです
問題は、次のフォームコントロールのエラーを削除するカスタム検証メソッドにありました。この方法を忘れました。助けてくれてありがとう。
validateCustomerDetails(g: FormGroup) {
if ((isNullOrUndefined(g.get('registration').value) || g.get('registration').value == "") &&
(isNullOrUndefined(g.get('customer_surname').value) || g.get('customer_surname').value == "")) {
g.controls['registration'].setErrors({ 'empty': true });
g.controls['customer_surname'].setErrors({ 'empty': true });
}
else {
g.controls['registration'].setErrors(null);
g.controls['customer_surname'].setErrors(null);
}
*ngIf="addLockerForm.controls?.registration?.invalid && addLockerForm.controls?.registration?.touched"
this.addLockerForm = formbuilder.group({
registration: [
"",
[
Validators.required,
Validators.minLength(4),
Validators.maxLength(8),
Validators.pattern(Your Pattern)
]
]
}
UがFormBuilderおよびValidatorを使用している場合、TsファイルでFormBuilderを使用します
次のコードを試してください
<mat-form-field class="input-label-add">
<input matInput placeholder="Registration **" formControlName="registration">
<div *ngIf="registration.errors">
<mat-error *ngIf="addLockerForm.get('registration').errors.maxlength">
registration cannot exceed 8 characters</mat-error>
<mat-error *ngIf="addLockerForm.get('registration').errors.required">registration or surname is required</mat-error>
</div>
</mat-form-field>