_limitItems.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. module.exports = function generate__limitItems(it, $keyword, $ruleType) {
  3. var out = ' ';
  4. var $lvl = it.level;
  5. var $dataLvl = it.dataLevel;
  6. var $schema = it.schema[$keyword];
  7. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  8. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  9. var $breakOnError = !it.opts.allErrors;
  10. var $errorKeyword;
  11. var $data = 'data' + ($dataLvl || '');
  12. var $isData = it.opts.$data && $schema && $schema.$data,
  13. $schemaValue;
  14. if ($isData) {
  15. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  16. $schemaValue = 'schema' + $lvl;
  17. } else {
  18. $schemaValue = $schema;
  19. }
  20. var $op = $keyword == 'maxItems' ? '>' : '<';
  21. out += 'if ( ';
  22. if ($isData) {
  23. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  24. }
  25. out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  26. var $errorKeyword = $keyword;
  27. var $$outStack = $$outStack || [];
  28. $$outStack.push(out);
  29. out = ''; /* istanbul ignore else */
  30. if (it.createErrors !== false) {
  31. out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
  32. if (it.opts.messages !== false) {
  33. out += ' , message: \'should NOT have ';
  34. if ($keyword == 'maxItems') {
  35. out += 'more';
  36. } else {
  37. out += 'less';
  38. }
  39. out += ' than ';
  40. if ($isData) {
  41. out += '\' + ' + ($schemaValue) + ' + \'';
  42. } else {
  43. out += '' + ($schema);
  44. }
  45. out += ' items\' ';
  46. }
  47. if (it.opts.verbose) {
  48. out += ' , schema: ';
  49. if ($isData) {
  50. out += 'validate.schema' + ($schemaPath);
  51. } else {
  52. out += '' + ($schema);
  53. }
  54. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  55. }
  56. out += ' } ';
  57. } else {
  58. out += ' {} ';
  59. }
  60. var __err = out;
  61. out = $$outStack.pop();
  62. if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
  63. if (it.async) {
  64. out += ' throw new ValidationError([' + (__err) + ']); ';
  65. } else {
  66. out += ' validate.errors = [' + (__err) + ']; return false; ';
  67. }
  68. } else {
  69. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  70. }
  71. out += '} ';
  72. if ($breakOnError) {
  73. out += ' else { ';
  74. }
  75. return out;
  76. }