UNPKG

9.15 kBMarkdownView Raw
1# Validate incoming objects against Swagger Models for Node.js
2[ ![Codeship Status for atlantishealthcare/swagger-model-validator](https://codeship.com/projects/a4ec3310-3b9b-0132-060c-1e7e00028aa9/status?branch=master)](https://codeship.com/projects/42728)
3[ ![npm version](https://badge.fury.io/js/swagger-model-validator.svg)](https://badge.fury.io/js/swagger-model-validator)
4
5[![NPM](https://nodei.co/npm/swagger-model-validator.png?downloads=true)](https://nodei.co/npm-dl/swagger-model-validator/)
6
7This is a validation module for [Swagger](https://github.com/swagger-api/swagger-spec) models (version 1.2 and 2.0) for Node.js.
8
9See the [swagger-node-express](https://github.com/swagger-api/swagger-node-express/blob/master/SAMPLE.md) sample for more details about Swagger in Node.js.
10
11## What's Swagger?
12The goal of Swaggerâ„¢ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swager removes the guesswork in calling the service.
13
14Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more.
15
16## Validating Swagger Models?
17A Swagger Model contains the definitions of the incoming (or outgoing) object properties. Validating an incoming object matches the Swagger Model Definition is a valuable check that the correct data has been provided.
18
19This package provides a module to do just that.
20
21## Swagger versions
22This project should work against both Swagger 1.2 and Swagger 2.0. Please create a pull request if you have any fixes for Swagger 2.0 support but please remember to retain support for Swagger 1.2 as well.
23
24### Validation Notes
25It will validate int32 properly but the way javascript handles int64 makes it impossible to accurately validate int64s.
26As long as the value can be parsed by parseInt in javascript it will be accepted as an int64.
27
28It currently treats float and decimal the same but this is because javascript cannot cope with a decimal (at the moment).
29As long as the value can be parsed by parseFloat in javascript it will be accepted as a float or a decimal.
30
31It validates the date and date-time correctly. It treats all dates (and date-times) as dates and tests with a parseDate
32check. If this passes then it checks 'date' format against a length of 10 (a quick check against the ISO8601 standard, a full-date must be 10 characters long).
33
34As from version 0.3 it will now validate models referenced by the $ref keyword but it will only do this if it is called
35by the swagger function validateModel or if the native validate is called with a model array passed in.
36
37As from version 1.0.0 it will now validate arrays in models. It will validate arrays of a type and arrays of a $ref.
38### Installation
39Install swagger-model-validator
40
41```
42npm install swagger-model-validator
43```
44
45Create a validator and pass your swagger client into it.
46```
47var Validator = require('swagger-model-validator');
48var validator = new Validator(swagger);
49```
50
51Now you can call validateModel on swagger to validate an incoming json object.
52
53```
54var validation = swagger.validateModel("modelName", jsonObject, _allowBlankTarget_, _disallowExtraProperties_);
55```
56
57This returns a validation results object
58
59```
60{
61 valid: true,
62 errorCount: 0
63}
64```
65or if validation fails
66```
67{
68 valid: false,
69 errorCount: 2,
70 errors: [
71 {
72 name: 'Error',
73 message: 'An error occurred'
74 },
75 {
76 name: 'Error',
77 message: 'Another error occurred'
78 }
79 ]
80}
81```
82
83You can also call the validation directly
84
85```
86var validation = validator.validate(object, swaggerModel, swaggerModels, allowBlankTarget, disallowExtraProperties);
87```
88
89will return the same validation results but requires the actual swagger model and not its name. _The swaggerModels
90parameter is required if you want models referenced by the $ref keyword to be validated as well._
91
92### Allowing blank targets to validate
93From 1.0.2 any empty objects passed in as targets will fail validation. You can bypass this by adding a `true` value to
94the method at the end.
95
96```
97var validation = swagger.validateModel("modelName", target, true);
98```
99
100This will allow an empty object `{ }` to be validated without errors. We consider a blank object to be worthless in most
101cases and so should normally fail, but there is always the chance that it might not be worthless so we've added the bypass.
102
103### Preventing extra properties
104From 1.2 an optional parameter can be passed into the validation request to control if extra properties should be disallowed.
105If this flag is true then the target object cannot contain any properties that are not defined on the model.
106If it is blank or false then the target object __can__ include extra properties (this is the default behaviour and the same
107as pre 1.2)
108
109```
110var validation = swagger.validateModel("modelName", target, true, true);
111```
112
113## Custom Field Validators
114You can add a custom field validator for a model to the validator from version 1.0.3 onwards. This allows you to add a
115function that will be called for any specific field that you need validated with extra rules.
116
117This function should be in the form
118```
119function(name, value) {
120 if(error) {
121 return new Error(error);
122 } else {
123 return null;
124 }
125}
126```
127It can return either a single Error object or an array of error objects. These errors will be passed back through the
128validator to the end user.
129
130### Adding a field validator
131Simply make a call to the validator method ```addFieldValidator``` providing the ```modelName```, ```fieldName``` and
132the validation function.
133
134```
135validator.addFieldValidator("testModel", "id", function(name, value) {
136 var errors = []
137 if(value === 34) {
138 errors.push(new Error("Value Cannot be 34"));
139 }
140
141 if(value < 40) {
142 errors.push(new Error("Value must be at least 40"));
143 }
144
145 return errors.length > 0 ? errors : null;
146});
147```
148Now the validator will call this extra function for the 'id' field in the 'testModel' model.
149
150You can add multiple custom validators to the same field. They will all be run. If a validator throws an exception it
151will be ignored and validation will continue.
152
153### Custom Field Validators for Swagger 2.0 Onwards
154Because the id property has been dropped from the model it is much harder to link models together in the validator.
155
156You can now add field validators as a custom property on each model by using the addFieldValidatorToModel function.
157
158```
159validator.addFieldValidatorToModel(model, "id", function(name, value) {
160 var errors = []
161 if(value === 34) {
162 errors.push(new Error("Value Cannot be 34"));
163 }
164
165 if(value < 40) {
166 errors.push(new Error("Value must be at least 40"));
167 }
168
169 return errors.length > 0 ? errors : null;
170});
171```
172
173## Handling Returned Errors
174Be careful with the results as javascript Errors cannot be turned into JSON without losing the message property.
175
176We have added two methods to help with this.
177
178GetErrorMessages() which returns an array of strings (one for each error) which contain the text of the error.message property.
179GetFormattedErrors() which returns an array of objects (one for each error) which contains all of the custom properties for each error and the text of the error.message property.
180
181Just passing the Validation Response errors array out will result in the loss of the error.message property. Most errors would appear as empty objects.
182
183## License
184Copyright (c) 2014 Atlantis Healthcare Limited.
185
186Permission is hereby granted, free of charge, to any person obtaining a copy
187of this software and associated documentation files (the "Software"), to deal
188in the Software without restriction, including without limitation the rights
189to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
190copies of the Software, and to permit persons to whom the Software is
191furnished to do so, subject to the following conditions:
192
193The above copyright notice and this permission notice shall be included in
194all copies or substantial portions of the Software.
195
196THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
197IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
198FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
199AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
200LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
201OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
202THE SOFTWARE.
203
\No newline at end of file