You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
959 B

4 years ago
  1. 'use strict';
  2. module.exports = function defFunc(ajv) {
  3. defFunc.definition = {
  4. type: 'string',
  5. inline: function (it, keyword, schema) {
  6. return getRegExp() + '.test(data' + (it.dataLevel || '') + ')';
  7. function getRegExp() {
  8. try {
  9. if (typeof schema == 'object')
  10. return new RegExp(schema.pattern, schema.flags);
  11. var rx = schema.match(/^\/(.*)\/([gimuy]*)$/);
  12. if (rx) return new RegExp(rx[1], rx[2]);
  13. throw new Error('cannot parse string into RegExp');
  14. } catch(e) {
  15. console.error('regular expression', schema, 'is invalid');
  16. throw e;
  17. }
  18. }
  19. },
  20. metaSchema: {
  21. type: ['string', 'object'],
  22. properties: {
  23. pattern: { type: 'string' },
  24. flags: { type: 'string' }
  25. },
  26. required: ['pattern'],
  27. additionalProperties: false
  28. }
  29. };
  30. ajv.addKeyword('regexp', defFunc.definition);
  31. return ajv;
  32. };