enum.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. module.exports = function generate_enum(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 $data = 'data' + ($dataLvl || '');
  11. var $valid = 'valid' + $lvl;
  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 $i = 'i' + $lvl,
  21. $vSchema = 'schema' + $lvl;
  22. if (!$isData) {
  23. out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
  24. }
  25. out += 'var ' + ($valid) + ';';
  26. if ($isData) {
  27. out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
  28. }
  29. out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
  30. if ($isData) {
  31. out += ' } ';
  32. }
  33. out += ' if (!' + ($valid) + ') { ';
  34. var $$outStack = $$outStack || [];
  35. $$outStack.push(out);
  36. out = ''; /* istanbul ignore else */
  37. if (it.createErrors !== false) {
  38. out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
  39. if (it.opts.messages !== false) {
  40. out += ' , message: \'should be equal to one of the allowed values\' ';
  41. }
  42. if (it.opts.verbose) {
  43. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  44. }
  45. out += ' } ';
  46. } else {
  47. out += ' {} ';
  48. }
  49. var __err = out;
  50. out = $$outStack.pop();
  51. if (!it.compositeRule && $breakOnError) {
  52. /* istanbul ignore if */
  53. if (it.async) {
  54. out += ' throw new ValidationError([' + (__err) + ']); ';
  55. } else {
  56. out += ' validate.errors = [' + (__err) + ']; return false; ';
  57. }
  58. } else {
  59. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  60. }
  61. out += ' }';
  62. if ($breakOnError) {
  63. out += ' else { ';
  64. }
  65. return out;
  66. }