or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

extensions-customization.mdindex.mdreferences-expressions.mdschema-types.mdutility-functions.mdvalidation-methods.md
tile.json

index.mddocs/

0

# Joi

1

2

Joi is a powerful schema description language and data validator for JavaScript that provides comprehensive object schema validation capabilities. It offers an expressive API for defining validation rules, data transformation, and error handling for JavaScript objects and values with built-in support for common data types, format validation, and the ability to create reusable schema patterns.

3

4

## Package Information

5

6

- **Package Name**: joi

7

- **Package Type**: npm

8

- **Language**: JavaScript with TypeScript definitions

9

- **Installation**: `npm install joi`

10

- **Node.js Requirements**: >= 20

11

12

## Core Imports

13

14

```javascript

15

const Joi = require('joi');

16

```

17

18

For ES modules:

19

20

```javascript

21

import Joi from 'joi';

22

```

23

24

TypeScript:

25

26

```typescript

27

import * as Joi from 'joi';

28

```

29

30

## Basic Usage

31

32

```javascript

33

const Joi = require('joi');

34

35

// Define a schema

36

const schema = Joi.object({

37

username: Joi.string()

38

.alphanum()

39

.min(3)

40

.max(30)

41

.required(),

42

43

password: Joi.string()

44

.pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),

45

46

email: Joi.string()

47

.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })

48

});

49

50

// Validate data

51

const { error, value } = schema.validate({

52

username: 'abc',

53

email: 'test@example.com'

54

});

55

56

if (error) {

57

console.log(error.details[0].message);

58

} else {

59

console.log('Valid data:', value);

60

}

61

62

// Async validation

63

try {

64

const value = await schema.validateAsync({

65

username: 'abc',

66

email: 'test@example.com'

67

});

68

console.log('Valid data:', value);

69

} catch (error) {

70

console.log('Validation error:', error.message);

71

}

72

```

73

74

## Architecture

75

76

Joi is built around several key components:

77

78

- **Schema Types**: Core validation types (string, number, object, array, etc.) providing type-specific validation rules

79

- **Validation Engine**: Synchronous and asynchronous validation with detailed error reporting

80

- **Reference System**: Dynamic validation using references to other fields or context values

81

- **Extension System**: Plugin architecture for custom validation types and rules

82

- **Template System**: Dynamic message generation and value interpolation

83

84

## Capabilities

85

86

### Schema Types

87

88

Core schema types for validating different data types with extensive configuration options and validation rules.

89

90

```typescript { .api }

91

function any(): AnySchema;

92

function string(): StringSchema;

93

function number(): NumberSchema;

94

function boolean(): BooleanSchema;

95

function array(): ArraySchema;

96

function object(schema?: SchemaMap): ObjectSchema;

97

function date(): DateSchema;

98

function function(): FunctionSchema;

99

function binary(): BinarySchema;

100

function symbol(): SymbolSchema;

101

function alternatives(...types: SchemaLike[]): AlternativesSchema;

102

function link(ref?: string): LinkSchema;

103

104

// Type aliases

105

const bool: typeof boolean;

106

const func: typeof function;

107

const alt: typeof alternatives;

108

```

109

110

[Schema Types](./schema-types.md)

111

112

### Validation Methods

113

114

Core validation functions for executing validation with comprehensive error handling and configuration options.

115

116

```typescript { .api }

117

function assert(value: any, schema: Schema, message?: string | Error, options?: ValidationOptions): any;

118

function attempt(value: any, schema: Schema, message?: string | Error, options?: ValidationOptions): any;

119

function compile(schema: SchemaLike, options?: CompileOptions): Schema;

120

function checkPreferences(prefs: ValidationOptions): void;

121

```

122

123

[Validation Methods](./validation-methods.md)

124

125

### References and Expressions

126

127

Dynamic validation system supporting field references, context access, and template expressions for advanced validation scenarios.

128

129

```typescript { .api }

130

function ref(key: string, options?: ReferenceOptions): Reference;

131

function in(ref: string, options?: ReferenceOptions): Reference;

132

function expression(template: string, options?: any): Template;

133

const x: typeof expression;

134

135

interface Reference {

136

readonly isContext: boolean;

137

readonly isGlobal: boolean;

138

readonly key: string;

139

readonly path: string[];

140

readonly ancestor: number;

141

}

142

143

interface Template {

144

readonly isTemplate: boolean;

145

render(context: any, prefs?: any, local?: any, options?: any): string;

146

}

147

```

148

149

[References and Expressions](./references-expressions.md)

150

151

### Extensions and Customization

152

153

Extension system for creating custom schema types, validation rules, and modifying default behavior.

154

155

```typescript { .api }

156

function extend(...extensions: Extension[]): Root;

157

function defaults(modifier: (schema: AnySchema) => AnySchema): Root;

158

159

interface Extension {

160

type: string | RegExp;

161

base?: Schema;

162

messages?: Record<string, string>;

163

coerce?: (value: any, helpers: CustomHelpers) => CoerceResult;

164

pre?: (value: any, helpers: CustomHelpers) => any;

165

language?: Record<string, string>;

166

describe?: (description: SchemaDescription) => SchemaDescription;

167

rules?: Record<string, RuleOptions>;

168

overrides?: Record<string, any>;

169

rebuild?: (schema: Schema) => Schema;

170

manifest?: ManifestOptions;

171

args?: (schema: Schema, ...args: any[]) => Schema;

172

}

173

```

174

175

[Extensions and Customization](./extensions-customization.md)

176

177

### Utility Functions

178

179

Helper functions for type checking, introspection, and working with joi objects and errors.

180

181

```typescript { .api }

182

function isSchema(schema: any, options?: any): boolean;

183

function isRef(ref: any): boolean;

184

function isExpression(expression: any): boolean;

185

function isError(error: any): boolean;

186

function types(): Record<string, Schema>;

187

188

const version: string;

189

const cache: CacheProvider;

190

const override: symbol;

191

```

192

193

[Utility Functions](./utility-functions.md)

194

195

## Global Configuration Types

196

197

```typescript { .api }

198

interface ValidationOptions {

199

abortEarly?: boolean;

200

allowUnknown?: boolean;

201

cache?: boolean;

202

context?: any;

203

convert?: boolean;

204

dateFormat?: 'date' | 'iso' | 'string' | 'time' | 'utc';

205

debug?: boolean;

206

errors?: ErrorFormattingOptions;

207

externals?: boolean;

208

messages?: LanguageMessages;

209

nonEnumerables?: boolean;

210

noDefaults?: boolean;

211

presence?: PresenceMode;

212

skipFunctions?: boolean;

213

stripUnknown?: boolean | { arrays?: boolean; objects?: boolean };

214

warnings?: boolean;

215

}

216

217

interface ErrorFormattingOptions {

218

escapeHtml?: boolean;

219

label?: 'path' | 'key' | false;

220

language?: string;

221

render?: boolean;

222

stack?: boolean;

223

wrap?: {

224

label?: string | false;

225

array?: string | false;

226

string?: string | false;

227

};

228

}

229

230

interface ValidationError extends Error {

231

name: 'ValidationError';

232

isJoi: true;

233

details: ValidationErrorItem[];

234

_original: any;

235

annotate(): string;

236

}

237

238

interface ValidationErrorItem {

239

message: string;

240

path: (string | number)[];

241

type: string;

242

context?: any;

243

}

244

245

interface ValidationResult<T = any> {

246

error?: ValidationError;

247

value: T;

248

warning?: ValidationError;

249

}

250

251

type PresenceMode = 'optional' | 'required' | 'forbidden';

252

type LanguageMessages = Record<string, string | Record<string, string>>;

253

```