首页 > 解决方案 > 动态更改表单控件验证并立即以角度反应形式应用新验证

问题描述

我有几个表单,我需要根据 #form1 用户选择对 #form2 输入进行自定义验证。我写了一个自定义验证(它还没有完成)。

自定义验证器:

@Injectable()
export class Checks {

    constructor(public prescConfigService: PrescConfigService) { }

    validity(section, key: string): ValidatorFn | null {
        const condition = this.prescConfigService.getDefaultSetting(section, key);
        if (!condition) {
            console.log('if there is no condition (not selected): ', condition);
            return (control: AbstractControl): { [key: string]: boolean } | null => {
                console.log('control1: ', control);
                return null;
            };
        } else {
            console.log('elseeeee', condition);
            return (control: AbstractControl): { [key: string]: boolean } | null => {
                console.log('control2: ', control);
                return { 'required': true };
            };
        }
    }
}

form2 创建:

this.form = this.fb.group({
      NationalNum: [this.prescConfigService.getValueByField('CustomerNationalNum'), {
        validator: [this.checks.validity('insurance', 'CheckNationalNum')],
        updateOn: 'change'
      }],
      BirthDateJalali: [this.prescConfigService.getValueByField('BirthDate'), Validators.required],
      Cellphone: [this.prescConfigService.getValueByField('Cellphone'), Validators.required],
      Sex: [this.prescConfigService.getValueByField('SexID'), Validators.required],
    });

我所需要的只是当用户从#form1(位于不同组件上)更改选择时应用自定义验证。到底有没有?

标签: angularvalidationangular-reactive-forms

解决方案


推荐阅读