Search code examples
javascriptangularjsng-required

apply ng-required if another element is selected


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


Solution

  • 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