-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick-start.ts
More file actions
183 lines (157 loc) · 6.77 KB
/
Copy pathquick-start.ts
File metadata and controls
183 lines (157 loc) · 6.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import { s, validate, validateAsync, Validator, ValidationError } from '../../dist/pure.js'
// ============================================================
// 1. Minimal schema — verify a single field
// ============================================================
const emailOnly = s({ email: 'email!' })
console.log('quick-start.emailOnly.valid =',
validate(emailOnly, { email: 'user@example.com' }).valid)
console.log('quick-start.emailOnly.invalid =',
validate(emailOnly, { email: 'bad' }).valid)
// ============================================================
// 2. User registration schema — multiple field types + chain API
// ============================================================
const registerSchema = s({
username: s('string:3-32!')
.pattern(/^[a-zA-Z0-9_]+$/)
.label('Username')
.error({ pattern: 'Only letters, digits and underscores are allowed' }),
email: s('email!').label('Email address'),
password: s('string:8-64!')
.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/)
.label('Password')
.error({ pattern: 'Must contain uppercase, lowercase and a digit' }),
age: 'number:18-120',
role: 'user|admin',
newsletter: s.boolean().default(false),
})
const validUser = {
username: 'john_doe',
email: 'john@example.com',
password: 'Password123',
age: 25,
role: 'user',
}
const invalidUser = {
username: 'john$', // invalid pattern
email: 'not-an-email', // invalid format
password: 'password', // missing uppercase + digit
age: 16, // below minimum
role: 'guest', // not in enum
}
const validResult = validate(registerSchema, validUser)
const invalidResult = validate(registerSchema, invalidUser)
console.log('quick-start.validUser.valid =', validResult.valid)
console.log('quick-start.validUser.data =', validResult.data)
console.log('quick-start.invalidUser.valid =', invalidResult.valid)
console.log('quick-start.invalidUser.errorCount =', invalidResult.errors?.length)
console.log('quick-start.invalidUser.errors =',
invalidResult.errors?.map(({ path, keyword, message }) => ({ path, keyword, message })))
// ============================================================
// 3. String coercion — form/query-string data often arrives as strings
// ============================================================
const orderSchema = s({
quantity: 'integer:1-100!',
price: 'number:0.01-',
discount: 'number:0-100',
})
// String values from HTML forms are automatically coerced to numbers
const fromForm = validate(orderSchema, { quantity: '3', price: '29.99', discount: '10' })
console.log('quick-start.coerce.valid =', fromForm.valid)
console.log('quick-start.coerce.quantity =',
(fromForm.data as Record<string, unknown>)?.quantity) // number 3, not string '3'
// Disable coercion when strict type checking is needed
const strictResult = validate(
orderSchema,
{ quantity: '3', price: '29.99' },
{ coerce: false },
)
console.log('quick-start.noCoerce.valid =', strictResult.valid) // false — strings rejected
// ============================================================
// 4. Nested objects and arrays
// ============================================================
const postSchema = s({
title: 'string:5-200!',
content: 'string:10-50000!',
tags: 'array:1-5<string:1-30>',
relatedProducts: s.array({
sku: 'string!',
quantity: 'integer:1-999!',
}).min(1),
published: 'boolean',
author: {
name: 'string:2-50!',
email: 'email',
avatar: 'url',
},
stats: {
views: 'integer:0-',
likes: 'integer:0-',
},
})
const validPost = {
title: 'Getting started with schema-dsl',
content: 'This comprehensive guide shows how to use schema-dsl for all your validation needs.',
tags: ['tutorial', 'typescript'],
relatedProducts: [{ sku: 'SKU-001', quantity: 2 }],
published: false,
author: {
name: 'Alice',
email: 'alice@example.com',
avatar: 'https://example.com/avatar.png',
},
stats: { views: 0, likes: 0 },
}
console.log('quick-start.post.valid =', validate(postSchema, validPost).valid)
const invalidPost = validate(postSchema, {
title: 'Hi', // too short (< 5 chars)
content: 'Short', // too short (< 10 chars)
tags: [], // empty array violates min:1
relatedProducts: [{ quantity: 0 }], // missing sku + quantity below minimum
author: { name: 'B', email: 'bad' }, // name too short, email invalid
stats: { views: -1, likes: 0 }, // views below minimum
})
console.log('quick-start.post.invalid.valid =', invalidPost.valid)
console.log('quick-start.post.invalid.errors =',
invalidPost.errors?.map(e => `${e.path}: ${e.keyword}`))
// ============================================================
// 5. Validator class — reusable instance with extended options
// ============================================================
const validator = new Validator({
allErrors: true, // collect all errors, not just the first
useDefaults: true, // apply schema default values to output data
cache: true, // cache compiled schemas for performance
})
// Validate a batch of records and collect per-item results
const batchResults = validator.validateBatch(registerSchema, [
{ username: 'alice_01', email: 'alice@example.com', password: 'Alice123', age: 28, role: 'user' },
{ username: 'bob_02', email: 'bob@example.com', password: 'Bob456Xx', age: 35, role: 'admin' },
{ username: 'ab', email: 'bad', password: 'short', age: 16, role: 'guest' },
])
console.log('quick-start.batch.results =', batchResults.map(r => r.valid))
// ============================================================
// 6. Pre-compiled function — zero parse overhead, best for hot paths
// ============================================================
// compile() returns a raw boolean function — fastest possible check
const compiled = validator.compile(registerSchema, 'user-register')
console.log('quick-start.compiled.valid =', compiled(validUser))
console.log('quick-start.compiled.invalid =', compiled(invalidUser))
console.log('quick-start.compiled.isFunction =', typeof compiled === 'function')
// ============================================================
// 7. Async validation — throws ValidationError on failure
// ============================================================
async function main(): Promise<void> {
const result = await validateAsync(registerSchema, validUser)
console.log('quick-start.async.valid.username =',
(result as { username: string }).username)
try {
await validateAsync(registerSchema, invalidUser)
} catch (err) {
if (err instanceof ValidationError) {
console.log('quick-start.async.invalid.caught =', true)
console.log('quick-start.async.invalid.errorCount =', err.errors.length)
} else {
throw err
}
}
}
void main()