LeanWX Validation blog
leanwx.com
HTML
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/black-tie/jquery-ui.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<div ng-controller='MainController'>
<form class='form' name="reservationForm">
<input name="reservationDate" datepicker validation-future-date placeholder="Reservation Date" ng-model="reservationDate" type="text" />
<div style="color: red" ng-show="reservationForm.reservationDate.$error.reservationDate">Please select a time that is in the future.</div>
<input name="reservationDate2" datepicker validation-future-date placeholder=" Date 2" ng-model="reservationDate2" type="text" />
</form>
</div>
JavaScript
var leanwxApp = angular.module('LeanwxApp', [], function () {});
var controllers = {};
controllers.MainController = function ($scope, $log) {
$scope.$watch("reservationDate", function (val, oldVal) {
$log.info(val, oldVal)
});
};
var directives = {};
directives.validationFutureDate = function () {
return {
require: '?ngModel',
link: function (scope, elm, attrs, ngModel) {
ngModel.$parsers.unshift(function (inputValue) {
var theDate, today;
var field = ngModel.$name;
;
//Validate empty field (ok!)
if (!inputValue) {
ngModel.$setValidity(field, true);
return;
}
//Make sure its a valid date...
theDate = Date.parse(inputValue);
if (isNaN(theDate) || theDate < 0) {
ngModel.$setValidity(field, false);
return theDate;
}
//and the crux... make sure its in the future!
today = new Date();
if (theDate <= today) {
ngModel.$setValidity(field, false);
return theDate;
}
//Success!
ngModel.$setValidity(field, true);
return theDate;
});
}
};
};
directives.datepicker = function ($log, $parse) {
return {
require: '?ngModel',
link: function (scope, element, attrs, ngModel) {
$log.info(ngModel);
$(element).datepicker({
inline: true,
onSelect: function (dateText) {
scope.$apply(function (scope) {
// Change binded variable
ngModel.$setViewValue(dateText);
});
}
});
}
...