7

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?

2
  • Careful, I was just reading about a custody battle in New York where the father had carried the baby (was pregnant). Talk about a corner case! Or, rounded, I suppose... Commented May 16, 2014 at 1:14
  • You can check my details answer. stackoverflow.com/questions/45498708/… Commented Jul 26, 2020 at 6:53

2 Answers 2

16

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @jacoviza, I am trying to do same type of Implementation like, there are two buttons(save and submit), and on click of submit there is need of required field validation for a text box, not on click of save. Can u share some idea for it.
3

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.

Comments

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.