b050149c7736bf42a49b48867eebe4d80413b2588b178cf2a89fd310b02160e78f41bc69ae3afba9263c94a094d1f085d7af8fe69098b8150601645ec5b03f 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import moment from 'moment';
  2. import {getNormalizedDate} from '../helpers/date';
  3. import {getEditorInstance} from '../editors';
  4. /**
  5. * Date cell validator
  6. *
  7. * @private
  8. * @validator DateValidator
  9. * @dependencies moment
  10. * @param {*} value - Value of edited cell
  11. * @param {Function} callback - Callback called with validation result
  12. */
  13. export default function dateValidator(value, callback) {
  14. let valid = true;
  15. const dateEditor = getEditorInstance('date', this.instance);
  16. if (value == null) {
  17. value = '';
  18. }
  19. let isValidDate = moment(new Date(value)).isValid() || moment(value, dateEditor.defaultDateFormat).isValid();
  20. // is it in the specified format
  21. let isValidFormat = moment(value, this.dateFormat || dateEditor.defaultDateFormat, true).isValid();
  22. if (this.allowEmpty && value === '') {
  23. isValidDate = true;
  24. isValidFormat = true;
  25. }
  26. if (!isValidDate) {
  27. valid = false;
  28. }
  29. if (!isValidDate && isValidFormat) {
  30. valid = true;
  31. }
  32. if (isValidDate && !isValidFormat) {
  33. if (this.correctFormat === true) { // if format correction is enabled
  34. let correctedValue = correctFormat(value, this.dateFormat);
  35. let row = this.instance.runHooks('unmodifyRow', this.row);
  36. let column = this.instance.runHooks('unmodifyCol', this.col);
  37. this.instance.setDataAtCell(row, column, correctedValue, 'dateValidator');
  38. valid = true;
  39. } else {
  40. valid = false;
  41. }
  42. }
  43. callback(valid);
  44. };
  45. /**
  46. * Format the given string using moment.js' format feature
  47. *
  48. * @param {String} value
  49. * @param {String} dateFormat
  50. * @returns {String}
  51. */
  52. export function correctFormat(value, dateFormat) {
  53. let dateFromDate = moment(getNormalizedDate(value));
  54. let dateFromMoment = moment(value, dateFormat);
  55. let isAlphanumeric = value.search(/[A-z]/g) > -1;
  56. let date;
  57. if ((dateFromDate.isValid() && dateFromDate.format('x') === dateFromMoment.format('x')) ||
  58. !dateFromMoment.isValid() ||
  59. isAlphanumeric) {
  60. date = dateFromDate;
  61. } else {
  62. date = dateFromMoment;
  63. }
  64. return date.format(dateFormat);
  65. };