DaveC426913 DaveC426913 - 1 year ago 117
AngularJS Question

Angular bootstrap conditionally-required fields

This seems to be very common, yet the solutions for it seem complex.

I've got a section of my form that is optional. If enabled, then its fields are required.

<!-- begin optional section -->
<h4>Trailer </h4>
<span>( optional </span>
<input class="input-inline" ng-model="hasTrailer" type="checkbox"/>
<h4 style="display: inline"> :</h4>

<div class="form-group">
<label for="trailerNumber"> Number:</label>
required />
ng-show="hasTrailer && form.trailerNumber.$invalid && form.trailerNumber.$touched || form.submitted">
<span> Trailer Number is required.</span >
<!-- end optional section -->

So, at the top of the section there is a checkbox, whose model is 'trailer'.
If checked, the fields are required.

What I really want is ideally:

<input type="text" required="hasTrailer">

or maybe

<input type="text" ng-attr({'required':hasTrailer})

i.e. if hasTrailer===true then required=true

Answer Source

You could use ng-required directive which will conditionally make input required when provided expression becomes true.

<input type="text" ng-required="hasTrailer">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download