1

I am creating a form in ionic2 in which fields changes as per categories changed by user dynamically.

if a field category is A is selected

then some fields such as start_date and time are required

but for category B only start_date is required

and for C both are not required.

I am using FormBuilder in ionic2 and validating like:

this.logForm = formBuilder.group({
        'start_date': ['', Validators.compose([Validators.maxLength(30),
                              Validators.required])],
        'time': ['', Validators.compose([Validators.maxLength(30),
                              Validators.required])],
    });

I am getting the selected category in an alert result like this:

category(){
   var options = {
      title: 'Choose a task category',
      inputs: [],
      message: 'Which category do you like?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Ok',
          handler: data => {}
        }
      ]
   }
}

In the handler of 'Ok' I can successfully retrieve the selected category.

So my question is how can i apply validation dynamically as per the category selected by user in app.

Community
  • 1
  • 1
Narendra Vyas
  • 717
  • 4
  • 9
  • 26

1 Answers1

1

You could try using setControl function in the formgroup api.

For example in the data handler of category:

()=>{
this.logForm.setControl('start_date',new FormControl('',Validators.required);
}

API of formControl here

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • Hi Suraj : I request you to please look at http://stackoverflow.com/questions/41373951/refresh-a-page-in-ionic2 . Thanks in advance – Narendra Vyas Dec 29 '16 at 06:40
  • Can you please help me in http://stackoverflow.com/questions/41930623/ionic2-cancel-api-request-if-timeout .. Thanks in advance. – Narendra Vyas Jan 30 '17 at 07:31
  • Hi Suraj: can you please help me in this http://stackoverflow.com/questions/42367946/array-with-custom-indexes-in-ionic2 (thanks in advance) – Narendra Vyas Feb 21 '17 at 13:36
  • Hi Suraj: can you please help me in this issue http://stackoverflow.com/questions/43113604/ionic2-ion-infinite-scroller-not-working-in-iphone .. Thanks in advance – Narendra Vyas Mar 30 '17 at 09:25