Sina Sohi
Sina Sohi

Reputation: 2779

Angular2 validator which relies on another form field

I am trying to create a validator in angular2 where I need to check the value of another form field. I have two scenarios I have tried where I have attempted to do this.

Scenario 1, form field looks like this:

Form = this._fb.group({
        ansat: ['', [<any>Validators.required]],
        helbred: ['', this.someValidator('ansat')],
    });

I have the two fields above, and I would like to be able to check the value of "ansat" in the validator function "someValidator". someValidator looks like this:

someValidator(key: string) {
    return (group: FormGroup) => {  
      console.log(group);
      console.log(group.controls[key].value);
    }
  }

In my function, group includes all the correct information for my formgroup, but "controls" is undefined, which means I cannot get to the value of "ansat.

Scenario 2, form field looks like this:

this.myForm = this._fb.group({
        ansat: ['', [<any>Validators.required]],
        helbred: ['', c => Validators.compose([
            this.someValidator(c,
                group => group.controls['ansat'].value === 0
            ),
        ])]
    });

And this is my someValidator function:

conditional(c, conditional) {
    console.log(conditional);
    console.log(c);

    if(c.parent != undefined || c._parent != undefined){
      if(c._parent.controls['ansat'].value === 0){
        console.log(c._parent.controls['ansat'].value);
      }
    }
    return null;
  }

In this case, the control "c", has the correct information and includes a parent which is the group it is allocated in, but I cannot access it to try and get it's brother in the same group.

And in the case of conditional parameter, I tried sending the group through a function which I cannot make to get working either.

QUESTION: I would like to be able to access the value of "ansat" inside of a validator that I call on "helbred". How do I do this?

Any help is greatly appreciated!

Upvotes: 0

Views: 539

Answers (1)

Riv
Riv

Reputation: 1859

Have a look at this plunker. You're on the right track, you must pass the actual ansat control in the helbred control's validator, instead of only passing ansat control's value.

ansat: AbstractControl = new FormControl('', Validators.required);
helbred: AbstractControl = new FormControl('', Validators.required, this.someValidator(this.ansat));

this.myForm = this.formBuilder.group({
        ansat: this.ansat,
        helbred: this.helbred
    });

Upvotes: 1

Related Questions