Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Validation in AngularJS

I need to apply a validation on a form field only if certain condition is met. Say I have a form like this:

<div ng-controller="MyController">
 <form name="myForm">
  <div>
   <div class="" ng-class="{error: myForm.gender.$invalid}">
    Gender:
   </div>
   Male   <input type="radio" name="gender" value="M" ng-model="survey.gender"   required/> 
   Female <input type="radio" name="gender" value="F" ng-model="survey.gender" required/> 
  </div>

  <div ng-show="survey.gender == 'F'">
   <div class="">
    Are you pregnant?
   </div>
   Yes <input type="radio" name="pregnant" value="Y" ng-model="survey.pregnant"/>
   No  <input type="radio" name="pregnant" value="N" ng-model="survey.pregnant"/>
  </div>
 </form>
</div>

I want to make the pregnant question required only if user picks female gender. Does Angular provides any kind of validation for this?

like image 829
jacoviza Avatar asked Jun 20 '13 15:06

jacoviza


2 Answers

Well, actually I just found the directive that does this. I only need to add ng-required="survey.gender == 'F'".

The code would look like this now:

<div ng-controller="MyController">
 <form name="myForm">
  <div>
   <div class="" ng-class="{error: myForm.gender.$invalid}">
    Gender:
   </div>
   Male   <input type="radio" name="gender" value="M" ng-model="survey.gender" required/> 
   Female <input type="radio" name="gender" value="F" ng-model="survey.gender" required/> 
  </div>

  <div ng-show="survey.gender == 'F'">
   <div class="">
    Are you pregnant?
   </div>
   Yes <input type="radio" name="pregnant" value="Y" ng-model="survey.pregnant" ng-required="survey.gender == 'F'">
   No  <input type="radio" name="pregnant" value="N" ng-model="survey.pregnant" ng-required="survey.gender == 'F'">
  </div>
 </form>
</div>
like image 155
jacoviza Avatar answered Sep 18 '22 12:09

jacoviza


Yes, take a look at ng-required. The documentation isn't good but there is some at that link.

Also here is a question that is similar to yours that was asked at an earlier date.

like image 36
hunt Avatar answered Sep 22 '22 12:09

hunt