enum.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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) { /* istanbul ignore if */
  52. if (it.async) {
  53. out += ' throw new ValidationError([' + (__err) + ']); ';
  54. } else {
  55. out += ' validate.errors = [' + (__err) + ']; return false; ';
  56. }
  57. } else {
  58. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  59. }
  60. out += ' }';
  61. if ($breakOnError) {
  62. out += ' else { ';
  63. }
  64. return out;
  65. }