Search code examples
angularjsvalidationinputnumbers

How to validate range between two number inputs using min and max attributes (AngularJs)


I'm having trouble validating a "from-to" range with AngularJs. The idea is to make a form valid only if the range is from lower to greater number.

// Script.js
var app = angular.module('app', []);

app.controller('RangeController', function ($scope) {
    $scope.data = [];
    $scope.data.from = 1;
    $scope.data.to = 10;
});

// HTML
<body ng-app="app">

    <div ng-controller="RangeController">
    
        <form name="myForm">
            From: <input type="number" ng-model="data.from" min="0" max="{{ data.to-1 }}" required />
            To: <input type="number" ng-model="data.to" min="{{ data.from+1 }}" required />
        </form>
        
        myForm.$valid = {{ myForm.$valid }}
    
    </div>
  
</body>

To reproduce undesired behavior open this plunker and type 50 in the "From" input and then type 75 in the "To" field.

With my mind set on "two way data binding" I wonder why didn't "from" input and form became valid when I typed 75 in to the "to" field.

I have searched a bit and found this discussion but I don't know does it really relates to my problem.

Any toughts?


Solution

  • Would it be possible to just prevent the user from entering anything but?

    Just keep them eyeing one another and when to changes set the other or if from changes set the to

    http://plnkr.co/edit/UQCstPAo7mKgROMz8pEB?p=preview

    app.directive('range',  function () {
        return {
            restrict: 'E',
            template: '' +
                '<div>' +
                    'From: <input type="number" ng-model="from" />' +
                    'To: <input type="number" ng-model="to" />' +
                '</div>',
            link: function ($scope, element, attrs) {
                $scope.$watch('from', function () { $scope.to = $scope.from + 1; });
                $scope.$watch('to', function () { $scope.from = $scope.to - 1; });
    
                $scope.from = 0;
            }
        };
    });