or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdschema-types.mdutilities.mdvalidation.md

index.mddocs/

0

# Yup

1

2

Yup is a comprehensive schema validation library for JavaScript that enables runtime value parsing, transformation, and assertion. It provides an extremely expressive and fluent API for building complex validation schemas that can model interdependent validations and value transformations with full TypeScript support and static type inference.

3

4

## Package Information

5

6

- **Package Name**: yup

7

- **Package Type**: npm

8

- **Language**: JavaScript/TypeScript

9

- **Installation**: `npm install yup`

10

11

## Core Imports

12

13

```typescript

14

import * as yup from "yup";

15

import { string, number, boolean, bool, date, object, array, tuple, mixed, ValidationError, ref, lazy } from "yup";

16

import type { InferType, Schema, ObjectSchema, ArraySchema } from "yup";

17

```

18

19

For CommonJS:

20

21

```javascript

22

const yup = require("yup");

23

const { string, number, boolean, bool, date, object, array, tuple, mixed, ValidationError, ref, lazy } = require("yup");

24

```

25

26

## Basic Usage

27

28

```typescript

29

import { object, string, number, InferType } from "yup";

30

31

// Define a schema

32

const userSchema = object({

33

name: string().required(),

34

email: string().email().required(),

35

age: number().positive().integer().min(18),

36

website: string().url().optional(),

37

});

38

39

// Infer TypeScript type

40

type User = InferType<typeof userSchema>;

41

42

// Validate data

43

try {

44

const user = await userSchema.validate({

45

name: "John Doe",

46

email: "john@example.com",

47

age: 25,

48

website: "https://johndoe.com"

49

});

50

console.log(user); // validated and potentially transformed data

51

} catch (error) {

52

console.error(error.errors); // validation error messages

53

}

54

55

// Synchronous validation

56

try {

57

const user = userSchema.validateSync(userData);

58

} catch (error) {

59

console.error(error.message);

60

}

61

```

62

63

## Architecture

64

65

Yup is built around several key architectural components:

66

67

- **Schema System**: Immutable schema objects that define validation rules and transformations

68

- **Type Hierarchy**: Base `Schema` class with specialized subclasses for different data types

69

- **Fluent API**: Chainable method calls for building complex validation rules

70

- **Async/Sync Validation**: Support for both asynchronous and synchronous validation

71

- **Type Safety**: Full TypeScript integration with `InferType` utility for static type extraction

72

- **Error Handling**: Comprehensive error reporting with detailed validation failure information

73

- **Extensibility**: Custom validation methods, transformations, and localization support

74

75

## Capabilities

76

77

### Schema Factory Functions

78

79

Core functions for creating typed validation schemas for different data types.

80

81

```typescript { .api }

82

function mixed<T = any>(spec?: MixedOptions): MixedSchema<T>;

83

function string(): StringSchema;

84

function number(): NumberSchema;

85

function boolean(): BooleanSchema;

86

function date(): DateSchema;

87

function object<T extends ObjectShape = {}>(shape?: T): ObjectSchema<T>;

88

function array<T = any>(innerType?: Schema<T>): ArraySchema<T>;

89

function tuple<T extends readonly [...any[]]>(types: T): TupleSchema<T>;

90

```

91

92

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

93

94

### Validation & Testing

95

96

Core validation methods, custom test functions, and error handling for robust data validation.

97

98

```typescript { .api }

99

// Core validation methods (available on all schemas)

100

validate(value: any, options?: ValidateOptions): Promise<T>;

101

validateSync(value: any, options?: ValidateOptions): T;

102

isValid(value: any, options?: ValidateOptions): Promise<boolean>;

103

cast(value: any, options?: CastOptions): T;

104

105

// Custom validation

106

test(name: string, message: string, testFn: TestFunction): Schema;

107

test(options: TestConfig): Schema;

108

```

109

110

[Validation & Testing](./validation.md)

111

112

### Utility Functions

113

114

Helper functions for schema manipulation, references, lazy evaluation, and localization.

115

116

```typescript { .api }

117

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

118

function lazy<T>(builder: (value: any, options: any) => Schema<T>): LazySchema<T>;

119

function reach(schema: Schema, path: string, value?: any, context?: any): Schema;

120

function addMethod(schemaType: Schema, name: string, method: Function): void;

121

function setLocale(localeObject: LocaleObject): void;

122

```

123

124

[Utilities](./utilities.md)

125

126

## Common Validation Patterns

127

128

### Object Schemas

129

130

```typescript

131

const personSchema = object({

132

firstName: string().required("First name is required"),

133

lastName: string().required("Last name is required"),

134

email: string().email("Invalid email").required(),

135

age: number().positive().integer().min(13, "Must be at least 13"),

136

});

137

```

138

139

### Array Validation

140

141

```typescript

142

const numbersSchema = array(number().positive()).min(1).max(10);

143

const usersSchema = array(personSchema).required();

144

```

145

146

### Conditional Validation

147

148

```typescript

149

const schema = object({

150

isBusiness: boolean(),

151

companyName: string().when("isBusiness", {

152

is: true,

153

then: (schema) => schema.required(),

154

otherwise: (schema) => schema.strip(),

155

}),

156

});

157

```

158

159

### Cross-Field References

160

161

```typescript

162

const passwordSchema = object({

163

password: string().min(8).required(),

164

confirmPassword: string()

165

.oneOf([ref("password")], "Passwords must match")

166

.required(),

167

});

168

```

169

170

## Type Definitions

171

172

```typescript { .api }

173

type InferType<T extends Schema> = T extends Schema<infer U> ? U : never;

174

type AnySchema = Schema<any>;

175

type AnyObject = Record<string, any>;

176

177

interface ValidateOptions<TContext = {}> {

178

strict?: boolean;

179

abortEarly?: boolean;

180

stripUnknown?: boolean;

181

recursive?: boolean;

182

context?: TContext;

183

}

184

185

interface CastOptions<TContext = {}> {

186

strict?: boolean;

187

stripUnknown?: boolean;

188

context?: TContext;

189

}

190

191

class ValidationError extends Error {

192

name: "ValidationError";

193

message: string;

194

value: any;

195

path?: string;

196

type?: string;

197

errors: string[];

198

inner: ValidationError[];

199

}

200

201

// Advanced utility types for schema composition

202

type Maybe<T> = T | null | undefined;

203

type Optionals<T> = Extract<T, null | undefined>;

204

type Defined<T> = T extends undefined ? never : T;

205

type NotNull<T> = T extends null ? never : T;

206

type Flags = 's' | 'd' | '';

207

type SetFlag<Old extends Flags, F extends Flags> = Exclude<Old, ''> | F;

208

type UnsetFlag<Old extends Flags, F extends Flags> = Exclude<Old, F> extends never ? '' : Exclude<Old, F>;

209

210

// Object schema utility types

211

type ObjectShape = { [k: string]: Schema<any> | Reference };

212

type TypeFromShape<S extends ObjectShape, _C> = {

213

[K in keyof S]: S[K] extends Schema<any> ? S[K]['__outputType'] : S[K] extends Reference<infer T> ? T : unknown;

214

};

215

type DefaultFromShape<Shape extends ObjectShape> = {

216

[K in keyof Shape]: Shape[K] extends Schema<any> ? Shape[K]['__default'] : undefined;

217

};

218

type MakePartial<T extends object> = Partial<T> & Required<NonOptionalKeys<T>>;

219

220

// Test configuration types

221

interface TestContext<T = any, C = any> {

222

path: string;

223

options?: ValidateOptions<C>;

224

parent?: any;

225

schema: Schema<T, C>;

226

resolve(value: T): T;

227

createError(params?: CreateErrorOptions): ValidationError;

228

}

229

230

type TestFunction<T = any, C = any> = (

231

value: T,

232

context: TestContext<T, C>

233

) => boolean | string | Promise<boolean | string>;

234

235

interface TestConfig<T = any, C = any> {

236

name?: string;

237

message?: string;

238

test: TestFunction<T, C>;

239

params?: object;

240

exclusive?: boolean;

241

skipAbsent?: boolean;

242

}

243

244

interface CreateErrorOptions {

245

path?: string;

246

message?: string;

247

params?: object;

248

}

249

```