0
# Data Validation
1
2
Validation system for verifying that real data matches specified Mock.js templates. Perfect for API contract testing, data integrity checks, and ensuring mock data accuracy during development.
3
4
## Capabilities
5
6
### Validation Function
7
8
Validate data against Mock.js templates to ensure structural and type consistency.
9
10
```javascript { .api }
11
/**
12
* Validate data against a template schema
13
* @param template - Mock.js template defining expected structure
14
* @param data - Real data to validate against template
15
* @returns Array of validation errors (empty array if valid)
16
*/
17
Mock.valid(template: any, data: any): ValidationError[];
18
19
interface ValidationError {
20
path: string[]; // Path to the invalid property
21
type: string; // Type of validation error
22
message: string; // Human-readable error message
23
expected: any; // Expected value or type
24
actual: any; // Actual value that failed validation
25
}
26
```
27
28
**Basic Validation Examples:**
29
30
```javascript
31
// Valid data
32
const template = {
33
name: '@string',
34
age: '@natural',
35
active: '@boolean'
36
};
37
38
const validData = {
39
name: 'John Doe',
40
age: 25,
41
active: true
42
};
43
44
const errors = Mock.valid(template, validData);
45
console.log(errors); // [] - no errors
46
47
// Invalid data
48
const invalidData = {
49
name: 123, // Should be string
50
age: 'twenty', // Should be number
51
active: 'yes' // Should be boolean
52
};
53
54
const errors2 = Mock.valid(template, invalidData);
55
console.log(errors2);
56
// [
57
// { path: ['name'], type: 'type', message: 'Expected string, got number', expected: 'string', actual: 123 },
58
// { path: ['age'], type: 'type', message: 'Expected number, got string', expected: 'number', actual: 'twenty' },
59
// { path: ['active'], type: 'type', message: 'Expected boolean, got string', expected: 'boolean', actual: 'yes' }
60
// ]
61
```
62
63
### Array Validation
64
65
Validate arrays against templates with generation rules.
66
67
```javascript
68
// Array template
69
const listTemplate = {
70
'items|1-10': [{
71
id: '@natural',
72
name: '@string',
73
'tags|0-3': '@string'
74
}]
75
};
76
77
// Valid array data
78
const validArray = {
79
items: [
80
{ id: 1, name: 'Item 1', tags: ['tag1', 'tag2'] },
81
{ id: 2, name: 'Item 2', tags: [] },
82
{ id: 3, name: 'Item 3', tags: ['tag1'] }
83
]
84
};
85
86
const arrayErrors = Mock.valid(listTemplate, validArray);
87
console.log(arrayErrors); // [] - valid
88
89
// Invalid array - wrong item structure
90
const invalidArray = {
91
items: [
92
{ id: '1', name: 'Item 1' }, // id should be number
93
{ name: 'Item 2', tags: 'invalid' } // missing id, tags should be array
94
]
95
};
96
97
const arrayErrors2 = Mock.valid(listTemplate, invalidArray);
98
console.log(arrayErrors2);
99
// Multiple validation errors for array items
100
```
101
102
### Nested Object Validation
103
104
Validate complex nested data structures.
105
106
```javascript
107
// Nested template
108
const userTemplate = {
109
id: '@natural',
110
profile: {
111
name: '@string',
112
contact: {
113
email: '@email',
114
phone: '@string'
115
},
116
'preferences|0-5': {
117
theme: '@string',
118
language: '@string'
119
}
120
},
121
'posts|0-10': [{
122
id: '@natural',
123
title: '@string',
124
'tags|1-5': '@string'
125
}]
126
};
127
128
// Test nested data
129
const userData = {
130
id: 123,
131
profile: {
132
name: 'John Smith',
133
contact: {
134
email: 'john@example.com',
135
phone: '+1-555-0123'
136
},
137
preferences: {
138
theme: 'dark',
139
language: 'en'
140
}
141
},
142
posts: [
143
{
144
id: 1,
145
title: 'My First Post',
146
tags: ['javascript', 'web']
147
}
148
]
149
};
150
151
const nestedErrors = Mock.valid(userTemplate, userData);
152
console.log(nestedErrors); // Validate nested structure
153
```
154
155
### Rule-based Validation
156
157
Validate data against specific Mock.js generation rules.
158
159
```javascript
160
// Template with rules
161
const rulesTemplate = {
162
'count|1-100': '@natural', // Should be 1-100
163
'status|1': ['active', 'inactive'], // Should be one of these values
164
'rating|1-5.1-2': '@float', // Should be 1-5 with 1-2 decimals
165
'items|3-8': '@string' // Should have 3-8 items
166
};
167
168
// Test data
169
const rulesData = {
170
count: 50, // Valid: within 1-100
171
status: 'active', // Valid: matches allowed values
172
rating: 4.5, // Valid: within range with correct decimals
173
items: ['a', 'b', 'c', 'd', 'e'] // Valid: 5 items within 3-8 range
174
};
175
176
const rulesErrors = Mock.valid(rulesTemplate, rulesData);
177
console.log(rulesErrors); // Check rule compliance
178
```
179
180
### Error Types
181
182
Different types of validation errors that can be returned.
183
184
```javascript { .api }
185
// Common error types:
186
// - 'type': Data type mismatch (string vs number, etc.)
187
// - 'format': Format validation failure (email, url, etc.)
188
// - 'range': Numeric value outside expected range
189
// - 'length': String/array length outside expected bounds
190
// - 'enum': Value not in allowed enumeration
191
// - 'required': Missing required property
192
// - 'structure': Object structure mismatch
193
```
194
195
**Error Handling Example:**
196
197
```javascript
198
function validateApiResponse(template, response) {
199
const errors = Mock.valid(template, response);
200
201
if (errors.length === 0) {
202
console.log('✓ API response is valid');
203
return true;
204
}
205
206
console.log('✗ API response validation failed:');
207
errors.forEach(error => {
208
const path = error.path.join('.');
209
console.log(` ${path}: ${error.message}`);
210
console.log(` Expected: ${JSON.stringify(error.expected)}`);
211
console.log(` Actual: ${JSON.stringify(error.actual)}`);
212
});
213
214
return false;
215
}
216
217
// Usage
218
const apiTemplate = {
219
success: '@boolean',
220
'data|1-50': [{
221
id: '@natural',
222
name: '@string',
223
email: '@email'
224
}]
225
};
226
227
const apiResponse = {
228
success: true,
229
data: [
230
{ id: 1, name: 'John', email: 'john@example.com' },
231
{ id: 2, name: 'Jane', email: 'invalid-email' } // Invalid email
232
]
233
};
234
235
validateApiResponse(apiTemplate, apiResponse);
236
```
237
238
### Schema Conversion
239
240
Convert Mock.js templates to JSON Schema format for validation.
241
242
```javascript { .api }
243
/**
244
* Convert Mock.js template to JSON Schema
245
* @param template - Mock.js template
246
* @param name - Schema name (optional)
247
* @param path - Internal path (for recursion)
248
* @returns JSON Schema object
249
*/
250
Mock.toJSONSchema(template: any, name?: string, path?: string[]): JSONSchema;
251
252
interface JSONSchema {
253
name: string;
254
template: any;
255
type: string;
256
rule: ParsedRule;
257
path: string[];
258
properties?: JSONSchema[]; // For objects
259
items?: JSONSchema[]; // For arrays
260
}
261
262
interface ParsedRule {
263
parameters: any[];
264
range: boolean;
265
min: number;
266
max: number;
267
count: number;
268
decimal: boolean;
269
dmin: number;
270
dmax: number;
271
dcount: number;
272
}
273
```
274
275
**Schema Conversion Example:**
276
277
```javascript
278
// Convert template to schema
279
const template = {
280
'users|5-10': [{
281
'id|+1': 1,
282
name: '@name',
283
'age|18-65': 1,
284
active: '@boolean'
285
}]
286
};
287
288
const schema = Mock.toJSONSchema(template);
289
console.log(JSON.stringify(schema, null, 2));
290
291
// Use schema for validation
292
const data = {
293
users: [
294
{ id: 1, name: 'John', age: 25, active: true },
295
{ id: 2, name: 'Jane', age: 30, active: false }
296
]
297
};
298
299
// Validate using the generated schema
300
const validationErrors = Mock.valid(template, data);
301
```
302
303
### Integration with Testing
304
305
Using validation in unit tests and API testing.
306
307
```javascript
308
// Jest test example
309
describe('API Response Validation', () => {
310
const responseTemplate = {
311
success: '@boolean',
312
message: '@string',
313
'data|0-100': [{
314
id: '@natural',
315
name: '@string',
316
email: '@email',
317
createdAt: '@datetime'
318
}]
319
};
320
321
test('should validate successful API response', () => {
322
const response = {
323
success: true,
324
message: 'Data retrieved successfully',
325
data: [
326
{
327
id: 123,
328
name: 'Test User',
329
email: 'test@example.com',
330
createdAt: '2023-04-15 10:30:00'
331
}
332
]
333
};
334
335
const errors = Mock.valid(responseTemplate, response);
336
expect(errors).toHaveLength(0);
337
});
338
339
test('should catch invalid API response', () => {
340
const response = {
341
success: 'true', // Should be boolean
342
message: 123, // Should be string
343
data: 'invalid' // Should be array
344
};
345
346
const errors = Mock.valid(responseTemplate, response);
347
expect(errors.length).toBeGreaterThan(0);
348
});
349
});
350
```