我正在处理表单,在多个阶段进行验证,很少有元素正常验证,很少元素在模糊时验证,其他元素在提交时验证。验证工作不正常。如果有人知道更好的处理方法,请告诉我。感谢
这是我的代码:
constructor(
private changeDetectorRef: ChangeDetectorRef,
private el: ElementRef,
private _snackBar: MatSnackBar ) {
this.form = new FormGroup({});
this.form.addControl(`firstname`, new FormControl(''));
this.form.addControl(`lastname`, new FormControl(''));
this.form.addControl(`title`, new FormControl('',
Validators.compose([Validators.required])));
this.form.addControl(
`email`,
new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$'),
])
)
);
this.form.addControl(
`phoneNumber`,
new FormControl('', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')]))
);
this.form.addControl(
`termsAndConditions`,
new FormControl('', Validators.compose([Validators.required]))
);
this.changeDetectorRef.markForCheck();
}
addValidation() {
this.form.controls['firstname'].setValidators([Validators.required, Validators.minLength(2)]);
this.form.controls['lastname'].setValidators([Validators.required, Validators.minLength(2)]);
}
removeValidation() {
this.form.controls['firstname'].setValidators([]);
this.form.controls['lastname'].setValidators([]);
}
onSubmit() {
this.addValidation();
// rest of my logic
}
onCancelBtnClick() {
this.form.reset();
this.removeValidation();
}
有一种更干净的方法。在构造函数中对代码进行一些更改,然后就不需要addValidation和removeValidation方法了。例如,我们在提交时对名字和姓氏进行验证,在模糊时对电子邮件进行验证。
this.form.addControl(`firstname`, new FormControl('', {
validators: Validators.compose([Validators.required, Validators.minLength(2)]), updateOn: 'submit'
}));
this.form.addControl(`lastname`, new FormControl('', {
validators: Validators.compose([Validators.required, Validators.minLength(2)]), updateOn: 'submit'
}));
this.form.addControl(`title`, new FormControl(''));
this.form.addControl(
`email`,
new FormControl(
'',
Validators.compose([
'', {
validators: Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$'),
])
]), updateOn: 'blur'
}
)
);