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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With