apply ng-required if another element is selected

63 Views Asked by At

I'm creating an optional part of a form. Once one of the two elements is selected (or text has been entered) the other is required but if there is no input for both these fields are not required. Can I accomplish this with ng-required? If not is there another way? Thanks for the help in advance!

Example Form

2

There are 2 best solutions below

0
On BEST ANSWER

You can just do a ng-required with the other model as parameter:

<input ng-model="myFirstInput" />
<input ng-model="mySecondInput"
       ng-required="myFirstInput" />

If the first input is filled in, myFirstInput will evaluate to truthy, so the second input will be required.

See this jsfiddle

0
On

you can use ng-required directive

<form name="myForm">

 Click here to make the input field required:

 <input type="checkbox" ng-model="myVar"><br><br>

 <input name="myInput" ng-model="myInput" ng-required="myVar">

 <h1 ng-if="!myForm.myInput.$valid">The input field cannot be empty</h1>

 </form>