pattern.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. module.exports = function generate_pattern(it, $keyword) {
  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 $isData = it.opts.v5 && $schema && $schema.$data,
  12. $schemaValue;
  13. if ($isData) {
  14. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  15. $schemaValue = 'schema' + $lvl;
  16. } else {
  17. $schemaValue = $schema;
  18. }
  19. var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
  20. out += 'if ( ';
  21. if ($isData) {
  22. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
  23. }
  24. out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { ';
  25. var $$outStack = $$outStack || [];
  26. $$outStack.push(out);
  27. out = ''; /* istanbul ignore else */
  28. if (it.createErrors !== false) {
  29. out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: ';
  30. if ($isData) {
  31. out += '' + ($schemaValue);
  32. } else {
  33. out += '' + (it.util.toQuotedString($schema));
  34. }
  35. out += ' } ';
  36. if (it.opts.messages !== false) {
  37. out += ' , message: \'should match pattern "';
  38. if ($isData) {
  39. out += '\' + ' + ($schemaValue) + ' + \'';
  40. } else {
  41. out += '' + (it.util.escapeQuotes($schema));
  42. }
  43. out += '"\' ';
  44. }
  45. if (it.opts.verbose) {
  46. out += ' , schema: ';
  47. if ($isData) {
  48. out += 'validate.schema' + ($schemaPath);
  49. } else {
  50. out += '' + (it.util.toQuotedString($schema));
  51. }
  52. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  53. }
  54. out += ' } ';
  55. } else {
  56. out += ' {} ';
  57. }
  58. var __err = out;
  59. out = $$outStack.pop();
  60. if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
  61. if (it.async) {
  62. out += ' throw new ValidationError([' + (__err) + ']); ';
  63. } else {
  64. out += ' validate.errors = [' + (__err) + ']; return false; ';
  65. }
  66. } else {
  67. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  68. }
  69. out += '} ';
  70. if ($breakOnError) {
  71. out += ' else { ';
  72. }
  73. return out;
  74. }