Mike Perrenoud
Mike Perrenoud

Reputation: 67898

ngRequired not setting $error property on the form field

I have a control that is conditionally visible and conditionally required based on the value of another field on the form.

<div class="form-group" ng-hide="vm.registration.typeId !== 2">
  <div class="row">
    <div class="col-md-offset-1 col-md-10">
      <label class='col-md-3' for="dischargeYear">Discharge Year*</label>
      <div class="col-md-7">
        <input type="text" id="dischargeYear" name="dischargeYear" 
               class="form-control large-text-form main-input"
               ng-model="vm.registration.dischargeYear"
               ng-required="vm.registration.typeId !== 2"
               ng-class="{'has-error': form.dischargeYear.$touched && form.dischargeYear.$invalid}">
      </div>
    </div>
  </div>
</div>

But, even though the $validators has the required validator on the dischargeYear on the form, it never has an error in $error. What's also interesting is I have another control that works, and the only difference is ng-required; the other control just marks up required.

Has anybody seen this before?

Upvotes: 0

Views: 31

Answers (2)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

In the end, the answer was to use ng-if on the surrounding div and just a required attribute on the input. This worked because it removed the element from the DOM when it wasn't needed, and recompiled it when it was.

<div class="form-group" ng-if="vm.registration.typeId === 2">
  <div class="row">
    <div class="col-md-offset-1 col-md-10">
      <label class='col-md-3' for="dischargeYear">Discharge Year*</label>
      <div class="col-md-7">
        <input type="text" id="dischargeYear" name="dischargeYear" 
               class="form-control large-text-form main-input"
               ng-model="vm.registration.dischargeYear"
               required
               ng-class="{'has-error': form.dischargeYear.$touched && form.dischargeYear.$invalid}">
      </div>
    </div>
  </div>
</div>

This caused the $validators and $error to get populated and the label to pop.

Upvotes: 1

Negi Rox
Negi Rox

Reputation: 3922

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">

<form name="myForm">

Click here to make the input field required:

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

<input name="name" ng-model="name" ng-required="setRequired">

<h1 ng-if="myForm.name.$invalid">The input field cannot be empty</h1>

</form>

</body>
</html>

Upvotes: 0

Related Questions