Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate child properties in angularjs?

I have model that looks like this:

$scope.item = {
    userId: 2,
    bioValues: [{
      name: 'Systolic',
      biometricValue: 120
    }, {
      name: 'Diastolic',
      biometricValue: 80
    }]
  };

My form names are "bioValues[0].biometricValue, bioValues1.biometricValue".

But when I try and validate my form, 'ng-show' on my field validation errors isn't triggered. I have looked at the form object in firebug and all of my applicable form errors are correctly marked as invalid when empty but ng-show isn't triggered.

Here is a plunker. Try leaving one of the inputs empty. The required error is not triggered on ng-show.

Any ideas? Thanks.

like image 538
trevorc Avatar asked Feb 26 '26 03:02

trevorc


1 Answers

There is no need to name the fields you are validating the exact name as the model that you are displaying.

Here is a working plunker.

The only change that I made was to name the fields in the template bioValues1 and bioValues2.

HTML:

<body ng-controller="MyCtrl">
  <form novalidate name="form">
    <div class="row">
      <input type="text" name="bioValues1" ng-model="item.bioValues[0].biometricValue" required />
      <span class="error" ng-show="form.bioValues1.$error.required">*Required</span>
    </div>
    <div class="row">
      <input type="text" name="bioValues2" ng-model="item.bioValues[1].biometricValue" required />
      <span class="error" ng-show="form.bioValues2.$error.required">*Required</span>
    </div>
  </form>
</body>

JS:

var myApp = angular.module("MyApp", []);

myApp.controller("MyCtrl", function($scope) {
  $scope.item = {
    userId: 2,
    bioValues: [{
      name: 'Systolic',
      biometricValue: 120
    }, {
      name: 'Diastolic',
      biometricValue: 80
    }]
  };

});
like image 63
Davin Tryon Avatar answered Feb 27 '26 16:02

Davin Tryon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!