var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.inputdate = "";
});
app.directive('myDirective', function () {
var dateRegExp = /^(\d{4})-(\d{2})-(\d{2})$/;
return {
// $parsers/$formatters live on the
// ngModel controller, so we need this!
require: 'ngModel',
link: function (scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function(value) {
console.log(value);
if (value === '' || value === null || value === undefined) {
// null means that there is no value which is fine
return null;
}
if (dateRegExp.test(value)) {
ngModel.$setValidity('errordateparsing',true);
return new Date(value);
}
else
{
ngModel.$setValidity('errordateparsing',false);
}
return undefined;
});
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.16/angular.js" data-semver="1.3.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div>Parser: do something to format user input
to be more "computer-friendly"</div>
<br/>
<form name="profileForm">
<input name="inputdate" type="text" my-directive ng-model="inputdate" /> {{inputdate}}
<div ng-show="profileForm.inputdate.$dirty && profileForm.inputdate.$invalid">
<span>Oh no! That does sound right!</span>
</div>
</form>
<pre>
{{ profileForm | json }}
</pre>
</body>
</html>
/* Put your css in here */
body {
font-family: sans-serif;
font-size: 24px;
}