2

I have a reactive form that has two fields: searchType and number. The field searchType can be '0' or '1' only. number is a number and number has some validation.

this.searchForm = this.formBuilder.group({
  searchType: ['0'],
  number: [
    undefined,
    [ Validators.required, Validators.minLength(6) ]
  ]
});

But now I want to add some specific validator for number only if searchType is 1. For example if searchType is 0 I have to use [ Validators.required, Validators.minLength(6) ], but if searchType is 1 I have to use [ Validators.required, Validators.minLength(8), Validators.minLength(20)]. How can I do that?

1 Answer 1

3

You can have a change event on your searchType, or then subscribe to valueChanges and then set the validators for your number form control.

searchtypeCtrl: FormControl;
numberCtrl: FormControl;

this.searchForm = this.formBuilder.group({
  searchType: ['0'],
  number: [undefined,[ Validators.required, Validators.minLength(6) ]]
});
// set form controls to variables
this.searchTypeCtrl = this.searchForm.get('searchType');
this.numberCtrl = this.searchForm.get('number');

and the valueChanges. As mentioned you could also listen to some change event and call a method that checks the value of the searchTypeCtrl and updates validators accordingly.

searchTypeCtrl.valueChanges.subscribe(value => {
  value === 0  ?  this.numberCtrl.setValidators([..conditional validators..]) :
                  this.numberCtrl.setValidators([..conditional validators..])

  this.numberCtrl.updateValueAndValidity();
})
Sign up to request clarification or add additional context in comments.

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.