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.

1 Answer 1

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

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

4 Comments

Hi Suraj : I request you to please look at stackoverflow.com/questions/41373951/refresh-a-page-in-ionic2 . Thanks in advance
Can you please help me in stackoverflow.com/questions/41930623/… .. Thanks in advance.
Hi Suraj: can you please help me in this stackoverflow.com/questions/42367946/… (thanks in advance)
Hi Suraj: can you please help me in this issue stackoverflow.com/questions/43113604/… .. Thanks in advance

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.