I am currently working on validating a three-part date field using AngularJS. I have managed to create a custom validation function, but I am struggling with determining how the fields should update each other's status.
How can I ensure that all three form fields are in sync and display their status as either valid or invalid based on the others?
You can find the fiddle here: http://jsfiddle.net/4GsMm/1/
Below is the code snippet:
<div ng-app="myApp" ng-controller="myCtrl">
<form action="" name="myForm">
<div class="date-group">
<input type="text" name="day" ng-model="day" ng-valid-func="validator" />
<input type="text" name="month" ng-model="month" ng-valid-func="validator" />
<input type="text" name="year" ng-model="year" ng-valid-func="validator" />
</div>
</form>
</div>
and...
input.ng-invalid{
background-color: #fdd !important;
}
input.ng-valid{
background-color: #dfd !important;
}
input{
display: inline;
width: 3em;
}
and...
var app = angular.module('myApp', [])
var myCtrl = function($scope){
$scope.day = "01"
$scope.month = "01"
$scope.year = "2000"
$scope.validator = function(val){
var day = $('[name=day]').val()
var month = $('[name=month]').val()
var year = $('[name=year]').val()
var d = new Date([year,month,day].join('-'))
console.log(d, [year,month,day].join('-'))
return d > new Date('2000-01-01')
}
}
app.directive('ngValidFunc', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (attrs.ngValidFunc && scope[attrs.ngValidFunc] && scope[attrs.ngValidFunc](viewValue, scope, elm, attrs, ctrl)) {
ctrl.$setValidity('custom', true);
} else {
ctrl.$setValidity('custom', false);
}
return elm.val()
});
}
};
});