validate.js 10 KB

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