Tsuna Sawada
Tsuna Sawada

Reputation: 349

How to validate if there is at least one checkbox selected out of 3 checkboxes in angularjs

Ok so this is the code:

<input name="chkbx1" type="checkbox"
    ng-model="LoanReferData.Prop1"
    ng-class="Submitted?'ng-dirty':''" required>Prop 1</input>

<input name="chkbx2" type="checkbox"
    ng-model="LoanReferData.Prop2" ng-class="Submitted?'ng-dirty':''"
    required>Prop 2</input>

<input name="chkbx3" type="checkbox" ng-model="LoanReferData.Prop3"
    ng-class="Submitted?'ng-dirty':''" required>Other</input>


<span class="error" ng-show="((frmLoanRefer.chkbx1.$dirty || Submitted) && frmLoanRefer.chkbx1.$error.required) || 
                                                            ((frmLoanRefer.chkbx2.$dirty || Submitted) && frmLoanRefer.chkbx2.$error.required) || 
                                                            ((frmLoanRefer.chkbx3.$dirty || Submitted) && frmLoanRefer.chkbx3.$error.required)  ">
                            * please select atleast 1 property is required.</span>

Upvotes: 0

Views: 283

Answers (2)

code4chicken
code4chicken

Reputation: 1

you can try with !frmLoanRefer.LoanReferData.Prop1 instead of frmLoanRefer.chkbx1.$dirty. The same for frmLoanRefer.chkbx2.$dirty and frmLoanRefer.chkbx3.$dirty

Upvotes: 0

rkalita
rkalita

Reputation: 575

You can add an 'ng-true-value' attribute in your inputs as example

<input name="chkbx1" type="checkbox" ng-true-value="true"
                            ng-model="LoanReferData.Prop1"
                            ng-class="Submitted?'ng-dirty':''" required>Prop 1</input>

<input name="chkbx2" type="checkbox" ng-true-value="true"
                            ng-model="LoanReferData.Prop2" ng-class="Submitted?'ng-dirty':''"
                            required>Prop 2</input>

<input name="chkbx3" type="checkbox" ng-model="LoanReferData.Prop3" ng-true-value="true"
                            ng-class="Submitted?'ng-dirty':''" required>Other</input>

{{LoanReferData}}

And here is an answer

{"Prop1":"true","Prop2":"true","Prop3":false}

Upvotes: 1

Related Questions