timeValidator.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. exports.__esModule = true;
  3. exports.default = timeValidator;
  4. var _moment = require('moment');
  5. var _moment2 = _interopRequireDefault(_moment);
  6. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7. // Formats which are correctly parsed to time (supported by momentjs)
  8. var STRICT_FORMATS = ['YYYY-MM-DDTHH:mm:ss.SSSZ', 'X', // Unix timestamp
  9. 'x' // Unix ms timestamp
  10. ];
  11. /**
  12. * Time cell validator
  13. *
  14. * @private
  15. * @validator TimeValidator
  16. * @dependencies moment
  17. * @param {*} value - Value of edited cell
  18. * @param {Function} callback - Callback called with validation result
  19. */
  20. function timeValidator(value, callback) {
  21. var valid = true;
  22. var timeFormat = this.timeFormat || 'h:mm:ss a';
  23. if (value === null) {
  24. value = '';
  25. }
  26. value = /^\d{3,}$/.test(value) ? parseInt(value, 10) : value;
  27. var twoDigitValue = /^\d{1,2}$/.test(value);
  28. if (twoDigitValue) {
  29. value += ':00';
  30. }
  31. var date = (0, _moment2.default)(value, STRICT_FORMATS, true).isValid() ? (0, _moment2.default)(value) : (0, _moment2.default)(value, timeFormat);
  32. var isValidTime = date.isValid();
  33. // is it in the specified format
  34. var isValidFormat = (0, _moment2.default)(value, timeFormat, true).isValid() && !twoDigitValue;
  35. if (this.allowEmpty && value === '') {
  36. isValidTime = true;
  37. isValidFormat = true;
  38. }
  39. if (!isValidTime) {
  40. valid = false;
  41. }
  42. if (!isValidTime && isValidFormat) {
  43. valid = true;
  44. }
  45. if (isValidTime && !isValidFormat) {
  46. if (this.correctFormat === true) {
  47. // if format correction is enabled
  48. var correctedValue = date.format(timeFormat);
  49. var row = this.instance.runHooks('unmodifyRow', this.row);
  50. var column = this.instance.runHooks('unmodifyCol', this.col);
  51. this.instance.setDataAtCell(row, column, correctedValue, 'timeValidator');
  52. valid = true;
  53. } else {
  54. valid = false;
  55. }
  56. }
  57. callback(valid);
  58. };