简体   繁体   中英

angular reactive form toggle validation required?

I have this radio button asking (do you have massage certificate?) if yes it will show the file input. I want this file input not required be default and if the user select yes it will become required. I have this code below that set cert validation to null by default and if has has_cert become true then set cert validator but its not working.. I need your help guys. Thanks in advance.

<p>Form value: {{ form.value | json }}</p>
<p>cert input : {{ form.get('cert').status | json }}</p>

.ts

form: FormGroup;
has_cert = new FormControl(false || true);
has_exp = new FormControl(false || true);
ngOnInit(): void {

    this.form = new FormGroup({
        ...
        has_cert: new FormControl(''),
        cert: new FormControl(''),
        ...
    })

    this.form.get("cert").setValidators(null);

    this.form.get('has_cert').valueChanges.pipe(
        filter(value => value === false || null)
    ).subscribe(
        () => this.form.get('cert').setValue(''),
        () => this.form.get("cert").setValidators(null)
    );

    this.form.get("has_cert").valueChanges.pipe(
        filter(value => value === true)
    ).subscribe(
        () => this.form.get("cert").setValidators(
            [
                Validators.required,
                Validators.pattern('^.*\.(doc|DOC|docx|DOCX|pdf|PDF)$')
            ]
        )
    );
}

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

You need to use form.get('something').setValidators(...) for each cases.

To add to @Liu Zhang's answer, I believe you can use clearValidators to remove all the validators you added with setValidators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM