0

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)$')
            ]
        )
    );
}

enter image description here

enter image description here

enter image description here

6
  • What's not working for you? Cross field validation or enable/disable of cert? Commented Apr 26, 2021 at 4:45
  • I yes, I want to enable validation when user select yes and disable validation when user select no Commented Apr 26, 2021 at 5:08
  • Got it! Can you can create a stackblitz fork? Commented Apr 26, 2021 at 5:26
  • 1
    You can use Cross Field validation angular.io/guide/form-validation#cross-field-validation Commented Apr 26, 2021 at 6:27
  • @NikhilWalvekar Hi, I have updated the code in my question Commented Apr 26, 2021 at 7:03

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Liu Zhang, I have tried that but Ican't remove the validator if has_cert become false this.form.get('has_cert').valueChanges.pipe( filter(value => value === false)) .subscribe(() => this.form.get('cert').setValue(''), () => this.form.get('cert').setValidators([]) );
Hi, I have updated the code in my question
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.