Why Angular 4 FormGroup custom validator not working?

六眼飞鱼酱① 提交于 2019-12-13 03:48:56

问题


Trying to add custom validator formValidator() on a form group. Depending on some condition I am setting the errors {invalidData: true}. But when the condition is false setting errors to null. The control2 itself has required validator. If I set errors to null, it will also clear the required validator.

Refer the below code,

createReactiveForm(data: any) {
    const formGroup = new FormGroup({
        'control1': new FormControl(data.value1),
        'control2': new FormControl(data.value2, [Validators.required])
    }, this.formValidator());
}

formValidator(): ValidatorFn {
    return (group: FormGroup): ValidationErrors => {
        const control1 = group.controls['control1'];
        const control2 = group.controls['control2'];
        if (control1.value === 'ABC' && control2.value !== 'ABC') {
            control2.setErrors({ invalidData: true });
        } else {
            control2.setErrors(null);
        }
        return;
    };
}

What is the solution for this? Or am I doing anything wrong in the custom validator? Please help.


回答1:


Validation functions aren't supposed to set errors on controls. They're supposed to return validation error objects.

formValidator(): ValidatorFn {
    return (group: FormGroup): ValidationErrors => {
        // use the abstraction provided by the framework
        const control1 = group.get('control1');
        const control2 = group.get('control2');
        // return the correct value depending on your condition
        return control1.value === 'ABC' && control2.value !== 'ABC' ? 
          { invalidData: true } : null;
    };
}


来源:https://stackoverflow.com/questions/52217086/why-angular-4-formgroup-custom-validator-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!