Angular2: Conditional required validation

Vanquiza picture Vanquiza · Nov 30, 2016 · Viewed 10.9k times · Source

I am trying to create a conditional required validation on a specific field.I try doing this by return Validators.required back in my function, but this doesn't seem to work. How do I go about doing this? Here's my code:

private _ansat: AbstractControl = new FormControl('', Validators.required);
private _helbred: AbstractControl = new FormControl('', Validators.compose([this.useValidateIfRadio(this._ansat, 0, Validators.required)]) );


constructor(private _fb: FormBuilder) {
    this.myForm = this._fb.group({
            ansat: this._ansat,
            helbred: this._helbred
        });
}

useValidateIfRadio (c: AbstractControl, n: number, v) {
        return function (control) {
            return new Promise(resolve => {
             // this.msg = ansatControl.value;
             console.log(v);
                if (c.value === n) {

                    resolve(v);
                }
                else {
                  resolve(null);

                }
            });
        };
    };

Any help is greatly appreciated.

Answer

Erex picture Erex · Feb 6, 2017

I had a similar problem but couldn't find a answer. Since nobody has answered this yet I'll provide an example of how I solved my problem, and how you can solve your issue using the same solution.

Example: (Phone number is required only if email is not set)

export class UserComponent implements OnInit {

userForm: FormGroup;

constructor(private fb: FormBuilder) {}

ngOnInit() {

    //Create my userForm and and add initial validators
    this.userForm = this.fb.group({
        username: [null, [Validators.required]],
        name: [null, [Validators.required]],
        email: [],
        phoneNumber: [null, [Validators.required, Validators.minLength(4)],
    });

    //Listen to email value and update validators of phoneNumber accordingly
    this.userForm.get('email').valueChanges.subscribe(data => this.onEmailValueChanged(data));
}


onEmailValueChanged(value: any){
    let phoneNumberControl = this.userForm.get('phoneNumber');

    // Using setValidators to add and remove validators. No better support for adding and removing validators to controller atm.
    // See issue: https://github.com/angular/angular/issues/10567
    if(!value){
        phoneNumberControl.setValidators([Validators.required, Validators.minLength(4)]);
    }else {
        phoneNumberControl.setValidators([Validators.minLength(4)]);
    }

    phoneNumberControl.updateValueAndValidity(); //Need to call this to trigger a update
}

}

So in your case you should add a changeListener to "_ansat" equal to my email listener, and then add required to "_helbred" accordingly.