如何在表单的开始和构建过程中执行验证。
我有以下代码:
// lef out imports
const noopValidatorFn: ValidatorFn = control => null;
@Component({
})
export class ProfileComponent implements OnChanges, OnInit {
// left out User variable.
get functionGroupsForm(): FormArray {
return this.accountForm.get('functionGroups') as FormArray;
}
buttonOptions = buttonOptions('Save');
accountForm: FormGroup;
requiredField = 'Field is required';
countries: string[] = ['Nederland', 'België', 'Duitsland'];
formErrors = {
firstName: '',
phoneNumber: '',
cellPhoneNumber: '',
};
validationMessages: any = {
firstName: { required: this.requiredField },
phoneNumber: { required: this.requiredField },
cellPhoneNumber: { required: 'Vul een mobiel of vast telefoonnummer in' }};
constructor(private readonly formBuilder: FormBuilder) {}
ngOnInit(): void {
this.role = this.authenticationService.getRole();
this.generatePhoneNumberValidationMessage();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.user) {
if (this.user) {
this.buildForm();
this.accountFormChange();
setTimeout(() => {
this.accountForm.patchValue(this.accountForm.value);
});
}
}
}
buildForm(): void {
this.accountForm = this.formBuilder.group({
firstName: [this.user.firstName, Validators.required],
phoneNumber: [this.user.phoneNumber, Validators.required],
cellPhoneNumber: [this.user.cellPhoneNumber, Validators.required],
});
// Object.keys(this.accountForm.controls).forEach(field => {
// const control = this.accountForm.get(field);
// control.updateValueAndValidity();
// });
// this.onValueChanged();
}
accountFormChange(): void {
this.accountForm.valueChanges.subscribe(() => {
if (this.role !== Role.Employee) {
const phoneNumber = this.accountForm.get('phoneNumber');
const cellPhoneNumber = this.accountForm.get('cellPhoneNumber');
if (!phoneNumber.value && !cellPhoneNumber.value) {
phoneNumber.setValidators([Validators.required]);
cellPhoneNumber.setValidators([Validators.required]);
} else {
if (phoneNumber.value) {
phoneNumber.setValidators([Validators.required]);
cellPhoneNumber.clearValidators();
}
if (cellPhoneNumber.value) {
cellPhoneNumber.setValidators([Validators.required]);
phoneNumber.clearValidators();
}
}
phoneNumber.updateValueAndValidity({ emitEvent: false });
cellPhoneNumber.updateValueAndValidity({ emitEvent: false });
}
this.buttonOptions.disabled = !this.accountForm.valid;
this.onValueChanged();
});
}
onValueChanged(): void {
const form = this.accountForm;
for (const field in this.formErrors) {
if (this.formErrors.hasOwnProperty(field)) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
if (control.errors.hasOwnProperty(key)) {
this.formErrors[field] += `${messages[key]} `;
}
}
}
}
}
}
}
我尝试了几种方法,例如patchValue setTimeout()。似乎没有任何作用。
电话号码是表格有效所必需的,但由于该值为空,因此应在ngOnChanges上立即显示错误消息。现在,它不显示任何错误消息,但是该按钮已禁用(因为尚未触发valueChanges)。
我怎么能得到这个结果?
编辑:忘记包含我的HTML
<div class="tab-content" *ngIf="user">
<form [formGroup]="accountForm">
<div class="form-block">
<div class="form-row">
<mat-form-field>
<input matInput placeholder="Firstname" formControlName="firstName" />
<mat-error *ngIf="formErrors.firstName">
{{ formErrors.firstName }}
</mat-error>
</mat-form-field>
</div>
<div class="form-row">
<mat-form-field>
<input matInput placeholder="Mobiel" type="number" formControlName="cellPhoneNumber" />
<mat-error *ngIf="formErrors.cellPhoneNumber">
{{ formErrors.cellPhoneNumber }}
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Telefoonnummer" type="number" formControlName="phoneNumber" />
<mat-error *ngIf="formErrors.phoneNumber">
{{ formErrors.phoneNumber }}
</mat-error>
</mat-form-field>
</div>
<div class="actions">
<mat-spinner-button (btnClick)="editAccountInformation()" [options]="buttonOptions" class="mat-spinner-color">
</mat-spinner-button>
</div>
</div>
</form>
</div>