propertyNames.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. module.exports = function defFunc(ajv) {
  3. defFunc.definition = {
  4. type: 'object',
  5. compile: function(schema) {
  6. var validate = ajv.compile(schema);
  7. return ajv._opts.allErrors ? vAllErrors : vBreakOnError;
  8. function vBreakOnError(data) {
  9. for (var prop in data) {
  10. if (!validate(prop)) {
  11. vBreakOnError.errors = validate.errors;
  12. addPropertyNameError(vBreakOnError.errors, prop);
  13. return false;
  14. }
  15. }
  16. return true;
  17. }
  18. function vAllErrors(data) {
  19. var errors = [];
  20. for (var prop in data) {
  21. if (!validate(prop)) {
  22. errors = errors.concat(validate.errors);
  23. addPropertyNameError(errors, prop);
  24. }
  25. }
  26. if (errors.length) vAllErrors.errors = errors;
  27. return errors.length == 0;
  28. }
  29. function addPropertyNameError(errors, propName) {
  30. errors.push({
  31. keyword: 'propertyNames',
  32. params: { propertyName: propName },
  33. message: 'should have valid property name of "' + propName + '"'
  34. });
  35. }
  36. },
  37. metaSchema: {
  38. $ref: ajv._opts.v5
  39. ? 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#'
  40. : 'http://json-schema.org/draft-04/schema#'
  41. },
  42. errors: true
  43. };
  44. ajv.addKeyword('propertyNames', defFunc.definition);
  45. return ajv;
  46. };