OrangePot
OrangePot

Reputation: 1082

HTML input validation (Angular) dependent on other fields

I have two fields which both take numbers. One must always be higher than the other. For example you can have a field for age, and then a field for older sibling age which of course must be greater depending on the first field.

My fields are like this:

<input type="number" ng-model="age" required> 

<input type="number" ng-model="olderSiblingAge" required>

I've tried using min="age" in the olderSibling input, but no luck, can still go below it.

Upvotes: 1

Views: 407

Answers (3)

lealceldeiro
lealceldeiro

Reputation: 14958

You have to interpolate the value like this: min="{{vm.age}}" as specified in the number input documentation regarding to AngularJS.

angular
  .module('app', [])
  .controller('ctrl', function() {
    var vm = this;
    vm.age = 1;
    vm.olderSiblingAge = 2;
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl as vm">
  <label> Age </label> <br />
  <input type="number" ng-model="vm.age" required ng-change="vm.olderSiblingAge = vm.age">

  <br /><br />

  <label> Older sibling age </label> <br />
  <input type="number" ng-model="vm.olderSiblingAge" required min="{{vm.age}}">
</div>

Note: I've used the controller-as syntax. Of course you can use it as your were doing it with the $scope notation like this min="{{age}}"

Upvotes: 2

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result, use below option of using ng-blur to compare entered values

code sample https://codepen.io/nagasai/pen/XEJpYa?editors=1010

HTML:

<div ng-app="test" ng-controller="testCtrl">
Age <input type="number" ng-model="age" required> 
Sibling Age <input type="number" ng-model="olderSiblingAge" required ng-blur="check()">{{olderSiblingAge}}

</div>

JS:

var app = angular.module('test',[]);

app.controller('testCtrl',function($scope){
    $scope.check = function(){
      if($scope.age  > $scope.olderSiblingAge){
         $scope.olderSiblingAge = null
        alert("older sibling age should be greater than age")
      }
    }
})

Upvotes: 0

Pavan Sikarwar
Pavan Sikarwar

Reputation: 798

TRY USING THIS CODE

<input type="number" ng-model="age" required> 

<input type="number" ng-change="olderSiblingAge = (olderSiblingAge < age)?age+1:olderSiblingAge" ng-model="olderSiblingAge" required>

Upvotes: 0

Related Questions