Angular 2中的验证非常简单,非常棒。但是,如果选择了其他字段,如何使必填字段可选。
这是我的规则
this.contractsFilter = this.fb.group({
selectedContractType: ['', [Validators.required]],
selectedYear: ['', [Validators.required]],
selectedPde: ['', [Validators.required]],
refNo: ['', []]
});
如果refNo由用户提供,我希望标记为必需的其他字段为“不需要”。
答案 0 :(得分:3)
使用自定义验证器和setValidators
都会非常复杂。我更喜欢配置验证器,因为它们可能是必需的,然后有条件地启用或禁用它们。
完全使用您的代码:
this.contractsFilter = this.fb.group({
selectedContractType: ['', [Validators.required]],
selectedYear: ['', [Validators.required]],
selectedPde: ['', [Validators.required]],
refNo: ['', []]
});
然后我会为valueChanges
订阅refNo
:
this.contractsFilter.controls['refNo'].valueChanges.subscribe(value => {
if (value) { // There is a refNo specified
this.contractsFilter.controls['selectedContractType'].disable();
this.contractsFilter.controls['selectedYear'].disable();
this.contractsFilter.controls['selectedPde'].disable();
} else {
this.contractsFilter.controls['selectedContractType'].enable();
this.contractsFilter.controls['selectedYear'].enable();
this.contractsFilter.controls['selectedPde'].enable();
}
});
现在您的验证器都在一个一致的位置指定,您仍然可以控制验证器是否被执行。
答案 1 :(得分:2)
以下是如何动态添加或删除验证器到某些控件
private addValidator(control, validator) {
let existingValidators = control.validator;
control.setValidators(Validators.compose([existingValidators, validator]));
control.updateValueAndValidity();
}
删除验证器
private removeRequiredValidator(control, otherValidators) {
control.clearValidators();
if (otherValidators) {
control.setValidators(otherValidators);
}
control.updateValueAndValidity();
}
答案 2 :(得分:0)
利用setValidators
设置/取消设置表单控件的验证器
import {FormControl, Validators, FormGroup} from "@angular/forms";
onRefNoEntered() {
if(this.contractsFilter.controls['refNo'].value && this.contractsFilter.controls['refNo'].valid) {
this.contractsFilter.controls['selectedContractType'].setValidators(null);
this.contractsFilter.controls['selectedYear'].setValidators(null);
this.contractsFilter.controls['selectedPde'].setValidators(null);
}
else {
this.contractsFilter.controls['selectedContractType'].setValidators(Validators.required);
this.contractsFilter.controls['selectedYear'].setValidators(Validators.required);
this.contractsFilter.controls['selectedPde'].setValidators(Validators.required);
}
}
答案 3 :(得分:0)
我遇到了类似的问题,受this solution的启发,我做了类似的事情:
const control = new FormControl(null,
[this.conditionalValidator(Validators.required)],
[this.conditionalAsyncValidator(this.validatorService.customAsyncValidator(params))] );
private conditionalValidator(validator: ValidatorFn): ValidatorFn {
return (control: AbstractControl): ValidationErrors => {
if(this.condition) {
return null;
}
return validator(control);
}
}
private conditionalAsyncValidator(validator: AsyncValidatorFn): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors> | Promise<ValidationErrors> => {
if(this.condition2) {
return observableOf(null);
}
return validator(control);
}
}