<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.js"></script>
<script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div ng-app="validDateApp">
<h1>Simple date validation directive using MomentJS</h1>
<div ng-form="myForm" ng-controller="testController">
<label>Please enter a date:</label>
<input my-valid-date ng-model="myDate" name="myDateInput" type="text" placeholder="D-M-YYYY" />
<div class="output">
<code>myDate</code> value: {{ myDate }}
</div>
<div class="output">
<code>myForm.myDateInput</code> valid: <strong>{{ myForm.myDateInput.$valid }}</strong>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
var app = angular.module("validDateApp", []);
app.controller("testController", function ($scope) {
$scope.myDate = null;
});
app.directive("myValidDate", function () {
return {
require: "ngModel",
restrict: "A", // Attributes only
link: function (scope, elem, attr, ctrl) {
ctrl.$validators.bzValidDate = function(value) {
if (value === undefined || value === null || value === "") {
return true;
}
return moment(value, ["D-M-YYYY"], true).isValid();
}
}
}
});
/* Styles go here */
body {
font-family: Arial;
}
strong {
color: #0080FF;
}
input.ng-invalid {
background-color: #F78181;
}
.output {
margin: 5px 0;
}
# Simple data validation in AngularJS using MomentJS.
Use a directive to validate date input!