validate.js 10 KB

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