_formatLimit.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. 'use strict';
  2. var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
  3. var DATE_TIME_SEPARATOR = /t|\s/i;
  4. var COMPARE_FORMATS = {
  5. date: compareDate,
  6. time: compareTime,
  7. 'date-time': compareDateTime
  8. };
  9. var $dataMetaSchema = {
  10. type: 'object',
  11. required: [ '$data' ],
  12. properties: {
  13. $data: {
  14. type: 'string',
  15. anyOf: [
  16. { format: 'relative-json-pointer' },
  17. { format: 'json-pointer' }
  18. ]
  19. }
  20. },
  21. additionalProperties: false
  22. };
  23. module.exports = function (minMax) {
  24. var keyword = 'format' + minMax;
  25. return function defFunc(ajv) {
  26. defFunc.definition = {
  27. type: 'string',
  28. inline: require('./dotjs/_formatLimit'),
  29. statements: true,
  30. errors: 'full',
  31. dependencies: ['format'],
  32. metaSchema: {
  33. anyOf: [
  34. {type: 'string'},
  35. $dataMetaSchema
  36. ]
  37. }
  38. };
  39. ajv.addKeyword(keyword, defFunc.definition);
  40. ajv.addKeyword('formatExclusive' + minMax, {
  41. dependencies: ['format' + minMax],
  42. metaSchema: {
  43. anyOf: [
  44. {type: 'boolean'},
  45. $dataMetaSchema
  46. ]
  47. }
  48. });
  49. extendFormats(ajv);
  50. return ajv;
  51. };
  52. };
  53. function extendFormats(ajv) {
  54. var formats = ajv._formats;
  55. for (var name in COMPARE_FORMATS) {
  56. var format = formats[name];
  57. // the last condition is needed if it's RegExp from another window
  58. if (typeof format != 'object' || format instanceof RegExp || !format.validate)
  59. format = formats[name] = { validate: format };
  60. if (!format.compare)
  61. format.compare = COMPARE_FORMATS[name];
  62. }
  63. }
  64. function compareDate(d1, d2) {
  65. if (!(d1 && d2)) return;
  66. if (d1 > d2) return 1;
  67. if (d1 < d2) return -1;
  68. if (d1 === d2) return 0;
  69. }
  70. function compareTime(t1, t2) {
  71. if (!(t1 && t2)) return;
  72. t1 = t1.match(TIME);
  73. t2 = t2.match(TIME);
  74. if (!(t1 && t2)) return;
  75. t1 = t1[1] + t1[2] + t1[3] + (t1[4]||'');
  76. t2 = t2[1] + t2[2] + t2[3] + (t2[4]||'');
  77. if (t1 > t2) return 1;
  78. if (t1 < t2) return -1;
  79. if (t1 === t2) return 0;
  80. }
  81. function compareDateTime(dt1, dt2) {
  82. if (!(dt1 && dt2)) return;
  83. dt1 = dt1.split(DATE_TIME_SEPARATOR);
  84. dt2 = dt2.split(DATE_TIME_SEPARATOR);
  85. var res = compareDate(dt1[0], dt2[0]);
  86. if (res === undefined) return;
  87. return res || compareTime(dt1[1], dt2[1]);
  88. }