JSFiddle - React, Tailwind, and code Playground
HTML
<div ng-app='formValidationApp'>
<form ng-controller="ValidationCtrl" name='rangesForm' novalidate>
<div class='line' ng-repeat='line in ranges' ng-form='lineForm'>
low: <input type='text'
name='low'
ng-pattern='/^\d+$/'
ng-change="lowChanged(this, $index)" ng-model='line.low' />
up: <input type='text'
name='up'
ng-pattern='/^\d+$/'
ng-change="upChanged(this, $index)"
ng-model='line.up' />
<a href ng-if='!$first' ng-click='removeRange($index)' >Delete</a>
<div class='error' ng-show='lineForm.$error.pattern'>
Must be a number.
</div>
<div class='error' ng-show='lineForm.$error.range'>
Low must be less the Up.
</div>
</div>
<a href ng-click='addRange()'>Add Range</a>
<input type='submit' ng-disabled='rangesForm.$invalid' />
</form>
</div>
CSS
.line {
clear: both;
}
input.ng-invalid {
border-color: red;
color: red;
background-color: pink;
}
.error{
color: red;
}
JavaScript
/**
* Example for http://MikitaManko.com/blog
*/
formValidationApp = angular.module('formValidationApp', []);
formValidationApp.controller('ValidationCtrl', ['$scope', function ($scope){
var scope_ = $scope;
$scope.ranges = [{low: 1}, {}, {}];
$scope.removeRange = function (index){
scope_.ranges.splice(index, 1);
};
$scope.addRange = function(){
scope_.ranges.push({});
};
$scope.lowChanged = function(scope, index) {
// check ranges
setValidity(
scope_.ranges[index].low,
scope_.ranges[index].up,
scope.lineForm.low);
// auto filling
if(index > 0) {
scope_.ranges[index - 1].up =
parseInt(scope_.ranges[index].low) - 1;
}
};
$scope.upChanged = function(scope, index) {
// check ranges
setValidity(
scope_.ranges[index].low,
scope_.ranges[index].up,
scope.lineForm.up);
// auto filling
if(index + 1 < scope_.ranges.length) {
scope_.ranges[index + 1].low =
parseInt(scope_.ranges[index].up) + 1;
}
}
function setValidity(low, up, element) {
if(low && up && !!+low && !!+up) {
element.$setValidity('range',
parseInt(low) < parseInt(up));
}
}
}]);