DaveC426913 DaveC426913 - 2 months ago 12
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 -->
<label>
<h4>Trailer </h4>
<span>( optional </span>
<input class="input-inline" ng-model="hasTrailer" type="checkbox"/>
<span>)</span>
<h4 style="display: inline"> :</h4>
</label>


<div class="form-group">
<label for="trailerNumber"> Number:</label>
<div>
<input
type="text"
name="trailerNumber"
ng-disabled="!hasTrailer"
ng-model="vm.Manifest.Trailer.number"
required />
</div>
<div>
<div
class="error-message"
ng-show="hasTrailer && form.trailerNumber.$invalid && form.trailerNumber.$touched || form.submitted">
<span> Trailer Number is required.</span >
</div>
</div>
</div>
<!-- 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

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

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