0
# Validation Methods
1
2
Core validation functions for executing validation with comprehensive error handling and configuration options.
3
4
## Capabilities
5
6
### Assert Function
7
8
Validates a value against a schema and throws a ValidationError if validation fails.
9
10
```typescript { .api }
11
/**
12
* Validates value against schema, throws ValidationError on failure
13
* @param value - Value to validate
14
* @param schema - Schema to validate against
15
* @param message - Optional custom error message or Error object
16
* @param options - Optional validation options
17
* @returns Validated and potentially transformed value
18
* @throws ValidationError if validation fails
19
*/
20
function assert(
21
value: any,
22
schema: SchemaLike,
23
message?: string | Error,
24
options?: ValidationOptions
25
): any;
26
```
27
28
**Usage Examples:**
29
30
```javascript
31
const Joi = require('joi');
32
33
const schema = Joi.string().min(3);
34
35
try {
36
// Successful validation returns the value
37
const result = Joi.assert('hello', schema);
38
console.log(result); // 'hello'
39
40
// Failed validation throws error
41
Joi.assert('hi', schema); // Throws ValidationError
42
} catch (error) {
43
console.log(error.message); // "value" length must be at least 3 characters long
44
}
45
46
// With custom message
47
try {
48
Joi.assert('hi', schema, 'Username too short');
49
} catch (error) {
50
console.log(error.message); // Username too short "value" length must be at least 3 characters long
51
}
52
53
// With Error object
54
try {
55
Joi.assert('hi', schema, new Error('Custom validation failed'));
56
} catch (error) {
57
console.log(error.message); // Custom validation failed
58
}
59
```
60
61
### Attempt Function
62
63
Validates a value against a schema and returns the validated value or throws an error.
64
65
```typescript { .api }
66
/**
67
* Validates value against schema, returns value or throws error
68
* @param value - Value to validate
69
* @param schema - Schema to validate against
70
* @param message - Optional custom error message or Error object
71
* @param options - Optional validation options
72
* @returns Validated and potentially transformed value
73
* @throws ValidationError if validation fails
74
*/
75
function attempt(
76
value: any,
77
schema: SchemaLike,
78
message?: string | Error,
79
options?: ValidationOptions
80
): any;
81
```
82
83
**Usage Examples:**
84
85
```javascript
86
const schema = Joi.object({
87
name: Joi.string().required(),
88
age: Joi.number().integer().min(0)
89
});
90
91
try {
92
const user = Joi.attempt({
93
name: 'John',
94
age: '25' // String will be converted to number
95
}, schema);
96
97
console.log(user); // { name: 'John', age: 25 }
98
console.log(typeof user.age); // 'number'
99
} catch (error) {
100
console.log('Validation failed:', error.message);
101
}
102
```
103
104
### Compile Function
105
106
Converts a literal schema description into a joi schema object.
107
108
```typescript { .api }
109
/**
110
* Converts literal schema description to joi schema object
111
* @param schema - Schema-like object or joi schema
112
* @param options - Optional compilation options
113
* @returns Compiled joi schema
114
*/
115
function compile(schema: SchemaLike, options?: CompileOptions): Schema;
116
117
interface CompileOptions {
118
legacy?: boolean;
119
}
120
```
121
122
**Usage Examples:**
123
124
```javascript
125
// Compile from literal object
126
const literalSchema = {
127
name: Joi.string().required(),
128
age: Joi.number()
129
};
130
131
const compiledSchema = Joi.compile(literalSchema);
132
133
// Use the compiled schema
134
const { error, value } = compiledSchema.validate({
135
name: 'Alice',
136
age: 30
137
});
138
139
// Compile with options
140
const legacySchema = Joi.compile(literalSchema, { legacy: true });
141
```
142
143
### Check Preferences Function
144
145
Validates preference objects to ensure they contain valid configuration options.
146
147
```typescript { .api }
148
/**
149
* Validates preference objects for correct configuration
150
* @param prefs - Preferences object to validate
151
* @throws Error if preferences are invalid
152
*/
153
function checkPreferences(prefs: ValidationOptions): void;
154
```
155
156
**Usage Examples:**
157
158
```javascript
159
// Valid preferences
160
Joi.checkPreferences({
161
abortEarly: false,
162
allowUnknown: true,
163
convert: false
164
});
165
166
// Invalid preferences will throw
167
try {
168
Joi.checkPreferences({
169
invalidOption: true,
170
convert: 'maybe' // Should be boolean
171
});
172
} catch (error) {
173
console.log('Invalid preferences:', error.message);
174
}
175
```
176
177
### Schema Validation Methods
178
179
Every schema instance provides validation methods for executing validation.
180
181
```typescript { .api }
182
interface BaseSchema<T = any> {
183
/**
184
* Synchronous validation returning result object
185
* @param value - Value to validate
186
* @param options - Optional validation options
187
* @returns ValidationResult with error and value properties
188
*/
189
validate(value: any, options?: ValidationOptions): ValidationResult<T>;
190
191
/**
192
* Asynchronous validation returning Promise
193
* @param value - Value to validate
194
* @param options - Optional validation options
195
* @returns Promise resolving to validated value or rejecting with ValidationError
196
*/
197
validateAsync(value: any, options?: ValidationOptions): Promise<T>;
198
199
/**
200
* Validation that throws on error, returns value on success
201
* @param value - Value to validate
202
* @param options - Optional validation options
203
* @returns Validated value
204
* @throws ValidationError if validation fails
205
*/
206
attempt(value: any, options?: ValidationOptions): T;
207
208
/**
209
* Validation that throws on error with detailed annotation
210
* @param value - Value to validate
211
* @param options - Optional validation options
212
* @returns Validated value
213
* @throws ValidationError if validation fails
214
*/
215
assert(value: any, options?: ValidationOptions): T;
216
}
217
218
interface ValidationResult<T = any> {
219
error?: ValidationError;
220
value: T;
221
warning?: ValidationError;
222
}
223
```
224
225
**Usage Examples:**
226
227
```javascript
228
const schema = Joi.object({
229
username: Joi.string().min(3).required(),
230
email: Joi.string().email()
231
});
232
233
const data = { username: 'jo', email: 'invalid-email' };
234
235
// Synchronous validation
236
const result = schema.validate(data);
237
if (result.error) {
238
console.log('Validation errors:', result.error.details);
239
} else {
240
console.log('Valid data:', result.value);
241
}
242
243
// Asynchronous validation
244
try {
245
const validData = await schema.validateAsync(data);
246
console.log('Valid data:', validData);
247
} catch (error) {
248
console.log('Validation failed:', error.details);
249
}
250
251
// Using attempt method
252
try {
253
const validData = schema.attempt(data);
254
console.log('Valid data:', validData);
255
} catch (error) {
256
console.log('Validation failed:', error.message);
257
}
258
259
// Using assert method
260
try {
261
const validData = schema.assert(data);
262
console.log('Valid data:', validData);
263
} catch (error) {
264
console.log('Detailed error:', error.annotate());
265
}
266
```
267
268
## Validation Options
269
270
```typescript { .api }
271
interface ValidationOptions {
272
// Validation behavior
273
abortEarly?: boolean; // Stop on first error (default: true)
274
allowUnknown?: boolean; // Allow unknown object keys (default: false)
275
cache?: boolean; // Enable validation caching (default: true)
276
convert?: boolean; // Enable type conversion (default: true)
277
debug?: boolean; // Enable debug mode (default: false)
278
externals?: boolean; // Process external validation (default: true)
279
noDefaults?: boolean; // Disable default value assignment (default: false)
280
nonEnumerables?: boolean; // Include non-enumerable properties (default: false)
281
presence?: PresenceMode; // Default presence requirement
282
skipFunctions?: boolean; // Skip function properties (default: false)
283
warnings?: boolean; // Enable warning collection (default: false)
284
285
// Unknown value handling
286
stripUnknown?: boolean | {
287
arrays?: boolean; // Strip unknown array items
288
objects?: boolean; // Strip unknown object keys
289
};
290
291
// Context and messages
292
context?: any; // Validation context object
293
messages?: LanguageMessages; // Custom error messages
294
295
// Date handling
296
dateFormat?: 'date' | 'iso' | 'string' | 'time' | 'utc';
297
298
// Error formatting
299
errors?: ErrorFormattingOptions;
300
}
301
302
interface ErrorFormattingOptions {
303
escapeHtml?: boolean; // Escape HTML in error messages
304
label?: 'path' | 'key' | false; // Label format in error messages
305
language?: string; // Language for error messages
306
render?: boolean; // Render error templates (default: true)
307
stack?: boolean; // Include stack traces (default: false)
308
wrap?: {
309
label?: string | false; // Characters around labels
310
array?: string | false; // Characters around arrays
311
string?: string | false; // Characters around strings
312
};
313
}
314
315
type PresenceMode = 'optional' | 'required' | 'forbidden';
316
type LanguageMessages = Record<string, string | Record<string, string>>;
317
```
318
319
**Usage Examples:**
320
321
```javascript
322
const schema = Joi.object({
323
name: Joi.string(),
324
age: Joi.number()
325
});
326
327
// Custom validation options
328
const options = {
329
abortEarly: false, // Collect all errors
330
allowUnknown: true, // Allow extra properties
331
convert: false, // Disable type conversion
332
stripUnknown: {
333
objects: true // Remove unknown object keys
334
},
335
messages: {
336
'string.base': 'Custom string error message'
337
}
338
};
339
340
const result = schema.validate(data, options);
341
342
// Context-aware validation
343
const contextOptions = {
344
context: {
345
userId: 123,
346
role: 'admin'
347
}
348
};
349
350
const contextResult = schema.validate(data, contextOptions);
351
```
352
353
## Error Handling
354
355
```typescript { .api }
356
interface ValidationError extends Error {
357
name: 'ValidationError';
358
isJoi: true;
359
details: ValidationErrorItem[];
360
_original: any;
361
362
/**
363
* Returns formatted error message with annotations
364
* @returns Annotated error string
365
*/
366
annotate(): string;
367
}
368
369
interface ValidationErrorItem {
370
message: string; // Error message
371
path: (string | number)[]; // Path to the error location
372
type: string; // Error type identifier
373
context?: { // Error context
374
key?: string; // Field key
375
label?: string; // Field label
376
value?: any; // Invalid value
377
[key: string]: any; // Additional context
378
};
379
}
380
```
381
382
**Usage Examples:**
383
384
```javascript
385
const schema = Joi.object({
386
nested: Joi.object({
387
value: Joi.string().required()
388
})
389
});
390
391
const { error } = schema.validate({ nested: {} });
392
393
if (error) {
394
console.log('Error details:', error.details);
395
// [{
396
// message: '"nested.value" is required',
397
// path: ['nested', 'value'],
398
// type: 'any.required',
399
// context: { key: 'value', label: 'nested.value' }
400
// }]
401
402
console.log('Annotated error:', error.annotate());
403
console.log('Original value:', error._original);
404
console.log('Is joi error:', error.isJoi); // true
405
}
406
```