Created
February 24, 2017 14:05
-
-
Save trinvh/98672ef764b70d705cee7436c3e3b451 to your computer and use it in GitHub Desktop.
Angular 1.x moment input directive with validators and formatters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function momentDateTime() { | |
var format = "YYYY-MM-DD HH:mm" | |
//date.isValid() is not enough for strict validation, see moment.js doc | |
var pattern = /^\s*\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}(:\d{2})?\s*$/ | |
return { | |
restrict: 'A', | |
require: 'ngModel', | |
link: function (scope, element, attr, ngModel) { | |
ngModel.$parsers.push(function (text) { | |
var date = moment(text, format); | |
ngModel.$validators.dateValid = function(modelValue, viewValue) { | |
return modelValue.isValid() && pattern.test(viewValue); | |
} | |
return date; | |
}) | |
ngModel.$formatters.push(function (datetime_moment) { | |
return datetime_moment && datetime_moment.local().format(format); | |
}) | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment