0
# Format Validation
1
2
Custom format registration system and built-in format validators for common data types. z-schema includes comprehensive format validators and allows registration of custom format validation functions.
3
4
## Capabilities
5
6
### Register Custom Format
7
8
Register a custom format validator function.
9
10
```javascript { .api }
11
/**
12
* Register a custom format validator
13
* @param formatName - Name of the custom format
14
* @param validatorFunction - Function that validates the format
15
*/
16
static registerFormat(
17
formatName: string,
18
validatorFunction: (value: any, callback?: (result: boolean) => void) => boolean
19
): void;
20
```
21
22
**Usage Examples:**
23
24
```javascript
25
const ZSchema = require("z-schema");
26
27
// Synchronous custom format
28
ZSchema.registerFormat("xstring", function(str) {
29
return str === "xxx";
30
});
31
32
// Asynchronous custom format
33
ZSchema.registerFormat("async-email", function(email, callback) {
34
// Simulate async validation (e.g., checking against database)
35
setTimeout(function() {
36
const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
37
callback(isValid);
38
}, 100);
39
});
40
41
// Custom format with complex validation
42
ZSchema.registerFormat("credit-card", function(cardNumber) {
43
if (typeof cardNumber !== "string") return false;
44
45
// Remove spaces and dashes
46
const cleaned = cardNumber.replace(/[\s-]/g, "");
47
48
// Check if all digits
49
if (!/^\d+$/.test(cleaned)) return false;
50
51
// Simple Luhn algorithm check
52
let sum = 0;
53
let shouldDouble = false;
54
55
for (let i = cleaned.length - 1; i >= 0; i--) {
56
let digit = parseInt(cleaned.charAt(i), 10);
57
58
if (shouldDouble) {
59
digit *= 2;
60
if (digit > 9) digit -= 9;
61
}
62
63
sum += digit;
64
shouldDouble = !shouldDouble;
65
}
66
67
return sum % 10 === 0;
68
});
69
70
// Use custom format in schema
71
const validator = new ZSchema();
72
const schema = {
73
type: "object",
74
properties: {
75
cardNumber: {
76
type: "string",
77
format: "credit-card"
78
}
79
}
80
};
81
82
const valid = validator.validate(
83
{ cardNumber: "4532-1234-5678-9012" },
84
schema
85
);
86
```
87
88
### Unregister Format
89
90
Remove a registered format validator.
91
92
```javascript { .api }
93
/**
94
* Remove a registered format validator
95
* @param formatName - Name of the format to remove
96
*/
97
static unregisterFormat(formatName: string): void;
98
```
99
100
**Usage Examples:**
101
102
```javascript
103
// Remove a custom format
104
ZSchema.unregisterFormat("xstring");
105
106
// Remove built-in format (not recommended)
107
ZSchema.unregisterFormat("email");
108
```
109
110
### Get Registered Formats
111
112
Get a list of all registered format names.
113
114
```javascript { .api }
115
/**
116
* Get array of all registered format names
117
* @returns Array of format names (built-in and custom)
118
*/
119
static getRegisteredFormats(): string[];
120
```
121
122
**Usage Examples:**
123
124
```javascript
125
const formats = ZSchema.getRegisteredFormats();
126
console.log("Available formats:", formats);
127
// Output: ["date", "date-time", "email", "hostname", "ipv4", "ipv6", "uri", ...]
128
129
// Check if a format is registered
130
if (formats.includes("credit-card")) {
131
console.log("Credit card format is available");
132
}
133
```
134
135
### Prefill Default Values
136
137
Use format validators to prefill default values into objects during validation.
138
139
```javascript { .api }
140
/**
141
* Format validator that modifies the object being validated
142
* Can be used to set default values or transform data
143
*/
144
// Example format that sets default values
145
ZSchema.registerFormat("fillDefaults", function(obj) {
146
if (typeof obj === "object" && obj !== null) {
147
if (!obj.hasOwnProperty("timestamp")) {
148
obj.timestamp = new Date().toISOString();
149
}
150
if (!obj.hasOwnProperty("version")) {
151
obj.version = "1.0.0";
152
}
153
}
154
return true;
155
});
156
```
157
158
**Usage Examples:**
159
160
```javascript
161
ZSchema.registerFormat("fillHello", function(obj) {
162
obj.hello = "world";
163
return true;
164
});
165
166
const validator = new ZSchema();
167
const schema = {
168
type: "object",
169
format: "fillHello"
170
};
171
172
const data = {};
173
validator.validate(data, schema);
174
console.log(data); // { hello: "world" }
175
```
176
177
## Built-in Format Validators
178
179
z-schema includes comprehensive built-in format validators:
180
181
### Date and Time Formats
182
183
```javascript { .api }
184
// Built-in date/time format validators
185
interface DateTimeFormats {
186
/** RFC3339 date format (YYYY-MM-DD) */
187
"date": (value: string) => boolean;
188
189
/** RFC3339 date-time format */
190
"date-time": (value: string) => boolean;
191
}
192
```
193
194
**Usage Examples:**
195
196
```javascript
197
const schema = {
198
type: "object",
199
properties: {
200
birthDate: { type: "string", format: "date" },
201
createdAt: { type: "string", format: "date-time" }
202
}
203
};
204
205
// Valid data
206
const valid = validator.validate({
207
birthDate: "1990-05-15",
208
createdAt: "2023-10-15T14:30:00Z"
209
}, schema);
210
```
211
212
### Network Formats
213
214
```javascript { .api }
215
// Built-in network format validators
216
interface NetworkFormats {
217
/** Email address format */
218
"email": (value: string) => boolean;
219
220
/** RFC1034 hostname format */
221
"hostname": (value: string) => boolean;
222
223
/** Alias for hostname */
224
"host-name": (value: string) => boolean;
225
226
/** IPv4 address format */
227
"ipv4": (value: string) => boolean;
228
229
/** IPv6 address format */
230
"ipv6": (value: string) => boolean;
231
232
/** URI format (RFC3986) */
233
"uri": (value: string) => boolean;
234
235
/** Strict absolute URI format */
236
"strict-uri": (value: string) => boolean;
237
}
238
```
239
240
**Usage Examples:**
241
242
```javascript
243
const schema = {
244
type: "object",
245
properties: {
246
email: { type: "string", format: "email" },
247
website: { type: "string", format: "uri" },
248
serverIP: { type: "string", format: "ipv4" },
249
hostname: { type: "string", format: "hostname" }
250
}
251
};
252
253
// Valid data
254
const valid = validator.validate({
255
email: "user@example.com",
256
website: "https://example.com/path",
257
serverIP: "192.168.1.1",
258
hostname: "api.example.com"
259
}, schema);
260
```
261
262
### Regular Expression Format
263
264
```javascript { .api }
265
// Built-in regex format validator
266
interface RegexFormat {
267
/** Validates regular expression syntax */
268
"regex": (value: string) => boolean;
269
}
270
```
271
272
**Usage Examples:**
273
274
```javascript
275
const schema = {
276
type: "object",
277
properties: {
278
pattern: { type: "string", format: "regex" }
279
}
280
};
281
282
// Valid regex patterns
283
const valid1 = validator.validate({
284
pattern: "^[a-zA-Z0-9]+$"
285
}, schema); // true
286
287
const valid2 = validator.validate({
288
pattern: "[invalid regex("
289
}, schema); // false
290
```
291
292
## Format Validation Options
293
294
### Strict URI Validation
295
296
Control URI format validation strictness through validator options.
297
298
```javascript { .api }
299
interface FormatOptions {
300
/** Require fully RFC3986 compliant URIs (default: false) */
301
strictUris?: boolean;
302
303
/** Don't report unknown formats as errors (default: false) */
304
ignoreUnknownFormats?: boolean;
305
}
306
```
307
308
**Usage Examples:**
309
310
```javascript
311
// Strict URI validation
312
const strictValidator = new ZSchema({
313
strictUris: true
314
});
315
316
const schema = { type: "string", format: "uri" };
317
318
// With strictUris: false (default)
319
validator.validate("relative/path", schema); // true
320
321
// With strictUris: true
322
strictValidator.validate("relative/path", schema); // false
323
strictValidator.validate("https://example.com", schema); // true
324
325
// Ignore unknown formats
326
const lenientValidator = new ZSchema({
327
ignoreUnknownFormats: true
328
});
329
330
const schemaWithUnknownFormat = {
331
type: "string",
332
format: "unknown-format"
333
};
334
335
// With ignoreUnknownFormats: false (default)
336
validator.validate("test", schemaWithUnknownFormat); // false (error)
337
338
// With ignoreUnknownFormats: true
339
lenientValidator.validate("test", schemaWithUnknownFormat); // true (ignored)
340
```
341
342
## Format Validation Error Handling
343
344
Format validation errors are reported with specific error codes and detailed information.
345
346
```javascript { .api }
347
interface FormatValidationError {
348
code: "INVALID_FORMAT" | "UNKNOWN_FORMAT";
349
message: string;
350
params: [string, any]; // [formatName, value]
351
path: string;
352
}
353
```
354
355
**Usage Examples:**
356
357
```javascript
358
const validator = new ZSchema();
359
const schema = {
360
type: "object",
361
properties: {
362
email: { type: "string", format: "email" }
363
}
364
};
365
366
const valid = validator.validate({
367
email: "invalid-email"
368
}, schema);
369
370
if (!valid) {
371
const errors = validator.getLastErrors();
372
errors.forEach(error => {
373
if (error.code === "INVALID_FORMAT") {
374
console.log(`Format validation failed for ${error.params[0]}: ${error.params[1]}`);
375
// Output: Format validation failed for email: invalid-email
376
}
377
});
378
}
379
```