2

I am working on angular 4 validation. I have a reactive form that have two radio button and two form groups. If user select's first radio button, it will remove validation from second form group and add validation on first form group and when select's second radio button it will add validation on second form group and remove from first form group.

Below is my form group example

this.mainForm = this.formBuilder.group({
    cardOrBank: new FormControl(''),
    cardDetails: new FormGroup({
        cardNo: new FormControl(''),
        cvv: new FormControl('')
    }),
    bankDetails: new FormGroup({
        accNo: new FormControl(''),
        ifsc: new FormControl('')
    })
});

HTML

<form [formGroup]="mainForm" (ngSubmit)="onFormSubmit()">
    <div>
        Select: <input type="radio" formControlName="cardOrBank"> card
        <input type="radio" formControlName="cardOrBank"> bank
    </div>
    <div formGroupName="cardDetails">
        <div>
            Card No: <input formControlName="cardNo">
        </div>
        <div>
            CVV: <input formControlName="cvv">
        </div>
    </div>
    <div formGroupName="bankDetails">
        <div>
            ACC No: <input formControlName="accNo">
        </div>
        <div>
            IFSC: <input formControlName="ifsc">
        </div>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</form>

If select card from radio button, it will add validation on cardDetails form and remove validation from bankDetails and vice versa.

P.S: Form fields may be more according to the requirement.

Thanks.

6
  • can you provide a working example? Commented Feb 14, 2019 at 12:29
  • Please share us your code, so that we can help you. Commented Feb 14, 2019 at 12:34
  • share us your html Commented Feb 14, 2019 at 12:39
  • question updated... Commented Feb 14, 2019 at 12:39
  • try as suggested you have to add and remove validation based on radio button click Commented Feb 14, 2019 at 12:49

4 Answers 4

3

After doing a lot of work finally i was able to achieve this.

Below are the changes you need to make in your code :

// in component.ts file  : 


// Write two genric methods which sets and clears the validator 

setRequireValidator(form:any){
  for (const field in form.controls) { // 'field' is a string
   let con = form.get(field); // 'control' is a FormControl
    con.setValidators([Validators.required]);
    con.updateValueAndValidity();
}

}

removeValidator(form:any){
  console.log('form contro',form);
  
  for (const field in form.controls) { // 'field' is a string
   let con = form.get(field); // 'control' is a FormControl
    con.clearValidators();
    con.updateValueAndValidity();
}
  
 
 // while initiallizing the form ragister the event for value changed on `cardOrBank`

// check which value user has selected and accordingly toggle between them 


 this.mainForm.get('cardOrBank').valueChanges.subscribe((val) => {
        const cardControl = this.mainForm.get('cardDetails');
        const bankControl = this.mainForm.get('bankDetails');
           if(val === 'card') {
           alert('card sletecd')
           this.removeValidator(bankControl);
          this.setRequireValidator(cardControl);

        } else{
             alert('bank sletecd')
          this.removeValidator(cardControl);
          this.setRequireValidator(bankControl);      
        }
   
 });
 
 
 
<!-- In component.html file-->


<form [formGroup]="mainForm" (ngSubmit)="onFormSubmit()">
    <div>
      <label>
      <!-- You missed value attribute --> 
     <input type="radio" value="card" formControlName="cardOrBank">
       <span>Card</span>
   </label>
   <label>
     <input type="radio" value="bank" formControlName="cardOrBank">
       <span>Bank</span>
   </label>
    </div>
    <div formGroupName="cardDetails">
        <div>
            Card No: <input formControlName="cardNo">
        </div>
        <div>
            CVV: <input formControlName="cvv">
        </div>
    </div>
    <div formGroupName="bankDetails">
        <div>
            ACC No: <input formControlName="accNo">
        </div>
        <div>
            IFSC: <input formControlName="ifsc">
        </div>
    </div>
    <div>
        <button type="submit" [disabled]="!mainForm.valid">Submit</button>
    </div>
</form>

Here is the Working Example of your requirement :

Working demo

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

Comments

1

you can do like this

addValidation() {
   this.form.get('title').setValidators([Validators.required, Validators.minLength(3)]);
   this.form.get('title').updateValueAndValidity();
}

removeValidation() {
 this.form.get('title').clearValidators();
 this.form.get('title').updateValueAndValidity();
}

Comments

0

You can do two things, either you can put explicit method or you can subscribe to the changes happens to formControlName to perform this validator switch.

if you want to subscribe then subscribe on ngOnInit() lifecycle hook:

      ngOnInit() {
         this.mainForm.get('cardDetails').valueChanges.subscribe((val) => {
           if(val === 'card') {
             this.mainForm.get('cardDetails').setValidators(Validators.required);
           } else {
             this.mainForm.get('bankDetails').removeValidators(Validators.required);
           }
         this.mainForm.get('bankDetails').updateValueAndValidity();
         });
        }

**add Value attribute in the html.**

**2nd Option :**



Select: <input type="radio" formControlName="cardOrBank (change)="changedPayment('card')"> card
 <input type="radio" formControlName="cardOrBank (change)="changedPayment('bank')> bank


    changedPayment(val) {
     if(val === 'card') {
             this.mainForm.get('cardDetails').setValidators(Validators.required);
           } else {
             this.mainForm.get('bankDetails').removeValidators(Validators.required);
           }
         this.mainForm.get('bankDetails').updateValueAndValidity();
    }

Comments

0

I assume that cardOrBank form control has two values 'card' and 'bank'. In your ngOnInit, you should subscribe the valueChanges of your radio button form control.

ngOnInit() {
 this.mainForm.get('cardDetails').valueChanges.subscribe((cardOrBank) => {
   if(cardOrBank === 'card') {
     this.mainForm.get('cardDetails').setValidators(Validators.required); 
     this.mainForm.get('bankDetails').removeValidators(Validators.required);

   } else {
     this.mainForm.get('bankDetails').setValidators(Validators.required); 
     this.mainForm.get('cardDetails').removeValidators(Validators.required);

   }                
   this.mainForm.get('bankDetails')updateValueAndValidity();                
   this.mainForm.get('cardDetails')updateValueAndValidity();

 });
}

Your radio button should have a value attribute

 <div>
      Select: <input type="radio" value="card" formControlName="cardOrBank"> card
      <input type="radio" value="bank" formControlName="cardOrBank"> bank
 </div>

2 Comments

thanks for the reply Bear Nithi......I have to remove the bankDetails formGroup validation while cardDetails are selected and also add bankDetails validation while bankDetails are selected.... May i am not sure but setValidators() function is used for formControl not for formGroup. just want to confirm
I have updated the code to remove validators on radio button selection

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.