validation.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import moment from 'moment';
  2. import * as dateMath from 'app/core/utils/datemath';
  3. export function inputDateDirective() {
  4. return {
  5. restrict: 'A',
  6. require: 'ngModel',
  7. link: ($scope, $elem, attrs, ngModel) => {
  8. const format = 'YYYY-MM-DD HH:mm:ss';
  9. const fromUser = text => {
  10. if (text.indexOf('now') !== -1) {
  11. if (!dateMath.isValid(text)) {
  12. ngModel.$setValidity('error', false);
  13. return undefined;
  14. }
  15. ngModel.$setValidity('error', true);
  16. return text;
  17. }
  18. let parsed;
  19. if ($scope.ctrl.isUtc) {
  20. parsed = moment.utc(text, format);
  21. } else {
  22. parsed = moment(text, format);
  23. }
  24. if (!parsed.isValid()) {
  25. ngModel.$setValidity('error', false);
  26. return undefined;
  27. }
  28. ngModel.$setValidity('error', true);
  29. return parsed;
  30. };
  31. const toUser = currentValue => {
  32. if (moment.isMoment(currentValue)) {
  33. return currentValue.format(format);
  34. } else {
  35. return currentValue;
  36. }
  37. };
  38. ngModel.$parsers.push(fromUser);
  39. ngModel.$formatters.push(toUser);
  40. },
  41. };
  42. }