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.

273 lines
11 KiB

  1. /**
  2. * JSONSchema Validator - Validates JavaScript objects using JSON Schemas
  3. * (http://www.json.com/json-schema-proposal/)
  4. *
  5. * Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
  6. * Licensed under the MIT (MIT-LICENSE.txt) license.
  7. To use the validator call the validate function with an instance object and an optional schema object.
  8. If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
  9. that schema will be used to validate and the schema parameter is not necessary (if both exist,
  10. both validations will occur).
  11. The validate method will return an array of validation errors. If there are no errors, then an
  12. empty list will be returned. A validation error will have two properties:
  13. "property" which indicates which property had the error
  14. "message" which indicates what the error was
  15. */
  16. (function (root, factory) {
  17. if (typeof define === 'function' && define.amd) {
  18. // AMD. Register as an anonymous module.
  19. define([], function () {
  20. return factory();
  21. });
  22. } else if (typeof module === 'object' && module.exports) {
  23. // Node. Does not work with strict CommonJS, but
  24. // only CommonJS-like environments that support module.exports,
  25. // like Node.
  26. module.exports = factory();
  27. } else {
  28. // Browser globals
  29. root.jsonSchema = factory();
  30. }
  31. }(this, function () {// setup primitive classes to be JSON Schema types
  32. var exports = validate
  33. exports.Integer = {type:"integer"};
  34. var primitiveConstructors = {
  35. String: String,
  36. Boolean: Boolean,
  37. Number: Number,
  38. Object: Object,
  39. Array: Array,
  40. Date: Date
  41. }
  42. exports.validate = validate;
  43. function validate(/*Any*/instance,/*Object*/schema) {
  44. // Summary:
  45. // To use the validator call JSONSchema.validate with an instance object and an optional schema object.
  46. // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
  47. // that schema will be used to validate and the schema parameter is not necessary (if both exist,
  48. // both validations will occur).
  49. // The validate method will return an object with two properties:
  50. // valid: A boolean indicating if the instance is valid by the schema
  51. // errors: An array of validation errors. If there are no errors, then an
  52. // empty list will be returned. A validation error will have two properties:
  53. // property: which indicates which property had the error
  54. // message: which indicates what the error was
  55. //
  56. return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false});
  57. };
  58. exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) {
  59. // Summary:
  60. // The checkPropertyChange method will check to see if an value can legally be in property with the given schema
  61. // This is slightly different than the validate method in that it will fail if the schema is readonly and it will
  62. // not check for self-validation, it is assumed that the passed in value is already internally valid.
  63. // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for
  64. // information.
  65. //
  66. return validate(value, schema, {changing: property || "property"});
  67. };
  68. var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) {
  69. if (!options) options = {};
  70. var _changing = options.changing;
  71. function getType(schema){
  72. return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase());
  73. }
  74. var errors = [];
  75. // validate a value against a property definition
  76. function checkProp(value, schema, path,i){
  77. var l;
  78. path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i;
  79. function addError(message){
  80. errors.push({property:path,message:message});
  81. }
  82. if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){
  83. if(typeof schema == 'function'){
  84. if(!(value instanceof schema)){
  85. addError("is not an instance of the class/constructor " + schema.name);
  86. }
  87. }else if(schema){
  88. addError("Invalid schema/property definition " + schema);
  89. }
  90. return null;
  91. }
  92. if(_changing && schema.readonly){
  93. addError("is a readonly field, it can not be changed");
  94. }
  95. if(schema['extends']){ // if it extends another schema, it must pass that schema as well
  96. checkProp(value,schema['extends'],path,i);
  97. }
  98. // validate a value against a type definition
  99. function checkType(type,value){
  100. if(type){
  101. if(typeof type == 'string' && type != 'any' &&
  102. (type == 'null' ? value !== null : typeof value != type) &&
  103. !(value instanceof Array && type == 'array') &&
  104. !(value instanceof Date && type == 'date') &&
  105. !(type == 'integer' && value%1===0)){
  106. return [{property:path,message:(typeof value) + " value found, but a " + type + " is required"}];
  107. }
  108. if(type instanceof Array){
  109. var unionErrors=[];
  110. for(var j = 0; j < type.length; j++){ // a union type
  111. if(!(unionErrors=checkType(type[j],value)).length){
  112. break;
  113. }
  114. }
  115. if(unionErrors.length){
  116. return unionErrors;
  117. }
  118. }else if(typeof type == 'object'){
  119. var priorErrors = errors;
  120. errors = [];
  121. checkProp(value,type,path);
  122. var theseErrors = errors;
  123. errors = priorErrors;
  124. return theseErrors;
  125. }
  126. }
  127. return [];
  128. }
  129. if(value === undefined){
  130. if(schema.required){
  131. addError("is missing and it is required");
  132. }
  133. }else{
  134. errors = errors.concat(checkType(getType(schema),value));
  135. if(schema.disallow && !checkType(schema.disallow,value).length){
  136. addError(" disallowed value was matched");
  137. }
  138. if(value !== null){
  139. if(value instanceof Array){
  140. if(schema.items){
  141. var itemsIsArray = schema.items instanceof Array;
  142. var propDef = schema.items;
  143. for (i = 0, l = value.length; i < l; i += 1) {
  144. if (itemsIsArray)
  145. propDef = schema.items[i];
  146. if (options.coerce)
  147. value[i] = options.coerce(value[i], propDef);
  148. errors.concat(checkProp(value[i],propDef,path,i));
  149. }
  150. }
  151. if(schema.minItems && value.length < schema.minItems){
  152. addError("There must be a minimum of " + schema.minItems + " in the array");
  153. }
  154. if(schema.maxItems && value.length > schema.maxItems){
  155. addError("There must be a maximum of " + schema.maxItems + " in the array");
  156. }
  157. }else if(schema.properties || schema.additionalProperties){
  158. errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties));
  159. }
  160. if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){
  161. addError("does not match the regex pattern " + schema.pattern);
  162. }
  163. if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){
  164. addError("may only be " + schema.maxLength + " characters long");
  165. }
  166. if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){
  167. addError("must be at least " + schema.minLength + " characters long");
  168. }
  169. if(typeof schema.minimum !== undefined && typeof value == typeof schema.minimum &&
  170. schema.minimum > value){
  171. addError("must have a minimum value of " + schema.minimum);
  172. }
  173. if(typeof schema.maximum !== undefined && typeof value == typeof schema.maximum &&
  174. schema.maximum < value){
  175. addError("must have a maximum value of " + schema.maximum);
  176. }
  177. if(schema['enum']){
  178. var enumer = schema['enum'];
  179. l = enumer.length;
  180. var found;
  181. for(var j = 0; j < l; j++){
  182. if(enumer[j]===value){
  183. found=1;
  184. break;
  185. }
  186. }
  187. if(!found){
  188. addError("does not have a value in the enumeration " + enumer.join(", "));
  189. }
  190. }
  191. if(typeof schema.maxDecimal == 'number' &&
  192. (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){
  193. addError("may only have " + schema.maxDecimal + " digits of decimal places");
  194. }
  195. }
  196. }
  197. return null;
  198. }
  199. // validate an object against a schema
  200. function checkObj(instance,objTypeDef,path,additionalProp){
  201. if(typeof objTypeDef =='object'){
  202. if(typeof instance != 'object' || instance instanceof Array){
  203. errors.push({property:path,message:"an object is required"});
  204. }
  205. for(var i in objTypeDef){
  206. if(objTypeDef.hasOwnProperty(i)){
  207. var value = instance[i];
  208. // skip _not_ specified properties
  209. if (value === undefined && options.existingOnly) continue;
  210. var propDef = objTypeDef[i];
  211. // set default
  212. if(value === undefined && propDef["default"]){
  213. value = instance[i] = propDef["default"];
  214. }
  215. if(options.coerce && i in instance){
  216. value = instance[i] = options.coerce(value, propDef);
  217. }
  218. checkProp(value,propDef,path,i);
  219. }
  220. }
  221. }
  222. for(i in instance){
  223. if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){
  224. if (options.filter) {
  225. delete instance[i];
  226. continue;
  227. } else {
  228. errors.push({property:path,message:(typeof value) + "The property " + i +
  229. " is not defined in the schema and the schema does not allow additional properties"});
  230. }
  231. }
  232. var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires;
  233. if(requires && !(requires in instance)){
  234. errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"});
  235. }
  236. value = instance[i];
  237. if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){
  238. if(options.coerce){
  239. value = instance[i] = options.coerce(value, additionalProp);
  240. }
  241. checkProp(value,additionalProp,path,i);
  242. }
  243. if(!_changing && value && value.$schema){
  244. errors = errors.concat(checkProp(value,value.$schema,path,i));
  245. }
  246. }
  247. return errors;
  248. }
  249. if(schema){
  250. checkProp(instance,schema,'',_changing || '');
  251. }
  252. if(!_changing && instance && instance.$schema){
  253. checkProp(instance,instance.$schema,'','');
  254. }
  255. return {valid:!errors.length,errors:errors};
  256. };
  257. exports.mustBeValid = function(result){
  258. // summary:
  259. // This checks to ensure that the result is valid and will throw an appropriate error message if it is not
  260. // result: the result returned from checkPropertyChange or validate
  261. if(!result.valid){
  262. throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n"));
  263. }
  264. }
  265. return exports;
  266. }));