dateValidator.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. var valid = true;
  15. var dateEditor = getEditorInstance('date', this.instance);
  16. if (value == null) {
  17. value = '';
  18. }
  19. var isValidDate = moment(new Date(value)).isValid() || moment(value, dateEditor.defaultDateFormat).isValid();
  20. // is it in the specified format
  21. var 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) {
  34. // if format correction is enabled
  35. var correctedValue = correctFormat(value, this.dateFormat);
  36. var row = this.instance.runHooks('unmodifyRow', this.row);
  37. var column = this.instance.runHooks('unmodifyCol', this.col);
  38. this.instance.setDataAtCell(row, column, correctedValue, 'dateValidator');
  39. valid = true;
  40. } else {
  41. valid = false;
  42. }
  43. }
  44. callback(valid);
  45. };
  46. /**
  47. * Format the given string using moment.js' format feature
  48. *
  49. * @param {String} value
  50. * @param {String} dateFormat
  51. * @returns {String}
  52. */
  53. export function correctFormat(value, dateFormat) {
  54. var dateFromDate = moment(getNormalizedDate(value));
  55. var dateFromMoment = moment(value, dateFormat);
  56. var isAlphanumeric = value.search(/[A-z]/g) > -1;
  57. var date = void 0;
  58. if (dateFromDate.isValid() && dateFromDate.format('x') === dateFromMoment.format('x') || !dateFromMoment.isValid() || isAlphanumeric) {
  59. date = dateFromDate;
  60. } else {
  61. date = dateFromMoment;
  62. }
  63. return date.format(dateFormat);
  64. };