valireq 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,39 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 - 2026-11-17
4
+
5
+ ### Bug Fixes
6
+
7
+ - **lowercase/uppercase dual-purpose conflict:** `lowercase` and `uppercase` are now sanitizers only (they transform the value). Added `isLowercase` and `isUppercase` as validation-only checks that reject non-conforming values without transforming them.
8
+ - **null + required interaction:** `null` values now trigger a `required` error (not `nullable`) when `required: true` is set. Previously, `null` always gave a `nullable` error even when the field was required.
9
+ - **Custom validator false positives:** Custom validators must now return exactly `true` to pass. Previously, any truthy value (including `1`, `"yes"`, etc.) was treated as passing, and falsy-but-valid values like `0` caused false positives.
10
+ - **Object/Array reference leak:** `type: 'object'` without `properties` and `type: 'array'` without `items` now return deep clones instead of raw input references. This prevents mutation of the original input through the validated output.
11
+ - **Date reference leak:** Date objects in output are now cloned. Previously, the same Date reference was shared between input and output.
12
+ - **Email regex too loose:** Email validation now rejects consecutive dots in the address and requires a TLD of at least 2 characters.
13
+ - **numeric regex too restrictive:** The `numeric` string check now accepts decimal strings (`"3.14"`) and negative strings (`"-5"`), not just unsigned integers.
14
+ - **Integer coercion:** Integer coercion now only coerces strings that represent safe integers. `"3.5"` is no longer coerced to `3.5` (it stays as a string and fails the type check).
15
+ - **normalizeEmail improved:** `normalizeEmail` now performs real email normalization — for Gmail/Googlemail addresses, it removes dots and plus-addressing from the local part.
16
+ - **Properties without type:object:** Setting `properties` on a rule now automatically processes the value as an object, even without explicit `type: 'object'`.
17
+ - **rejectEmpty return value:** Fields rejected by `rejectEmpty` now return `present: false`, excluding them from output.
18
+ - **Custom error messages for enum/oneOf:** `enum` and `oneOf` rules now respect custom `message` values.
19
+ - **Double options validation:** Options are now validated once at middleware creation time (not again per-request inside `validateData`). This catches configuration errors early at app startup.
20
+ - **Transform returning undefined:** A `transform` function returning `undefined` now correctly excludes the field from output.
21
+ - **Middleware uses normalized options consistently:** The error handler now reads from pre-normalized options.
22
+
23
+ ### New Features
24
+
25
+ - `isLowercase` — validation-only check that the string is already lowercase.
26
+ - `isUppercase` — validation-only check that the string is already uppercase.
27
+ - `minItems` — minimum number of items in an array.
28
+ - `maxItems` — maximum number of items in an array.
29
+
30
+ ### Improvements
31
+
32
+ - Comprehensive test suite expanded from 11 to 117 tests.
33
+ - Improved inline documentation and JSDoc comments.
34
+ - README rewritten with complete API reference, tables, and usage examples.
35
+
36
+ ## 0.1.0 - 2026-11-17
37
+
38
+ - Initial CommonJS validation engine and Express middleware.
39
+ - Added nested schemas, sanitization, coercion, defaults, custom async validators, cleanup policies, limits, tests, and documentation.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ValiReq contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
package/README.md CHANGED
@@ -1,3 +1,410 @@
1
- # Temporary Holding Version
1
+ # ValiReq
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Validate. Sanitize. Transform.**
4
+
5
+ ValiReq is a lightweight, production-quality request validation, sanitization and transformation toolkit for Express.js. It validates `body`, `query`, and `params` data, returns a new cleaned object (never mutating the original), and supports nested schemas, coercion, defaults, custom sync/async validators, and configurable unknown-field policies.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install valireq
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```js
16
+ const express = require('express');
17
+ const { validate } = require('valireq');
18
+
19
+ const app = express();
20
+ app.use(express.json());
21
+
22
+ app.post('/users', validate({
23
+ email: { required: true, type: 'string', trim: true, lowercase: true, email: true },
24
+ age: { type: 'number', coerce: true, min: 18 },
25
+ active: { type: 'boolean', coerce: true, default: true }
26
+ }), (req, res) => res.json(req.validated));
27
+
28
+ app.listen(3000);
29
+ ```
30
+
31
+ ## Features
32
+
33
+ - **Request validation** — validate `req.body`, `req.query`, and `req.params`.
34
+ - **Type checking** — `string`, `number`, `integer`, `boolean`, `array`, `object`, `date`.
35
+ - **String validation** — `email`, `url`, `uuid`, `alphanumeric`, `numeric`, `alphabetic`, `isLowercase`, `isUppercase`, `startsWith`, `endsWith`, `contains`, `matches`.
36
+ - **Number validation** — `min`, `max`, `integer`, `positive`, `negative`, `finite`.
37
+ - **Length validation** — `minLength`, `maxLength`, `exactLength`.
38
+ - **Enum & equality** — `enum`, `oneOf`, `equals`, `notEquals`.
39
+ - **Sanitization** — `trim`, `lowercase`, `uppercase`, `removeExtraSpaces`, `stripHtml`, `removeNullBytes`, `normalizeEmail`, `escapeHtml`.
40
+ - **Coercion** — string to number/integer/boolean/date with `coerce: true`.
41
+ - **Defaults & transforms** — `default`, `transform(value)`.
42
+ - **Nested schemas** — `properties` for objects, `items` for arrays.
43
+ - **Array constraints** — `minItems`, `maxItems`.
44
+ - **Unknown field handling** — `strip` (default), `strict`, `passthrough`.
45
+ - **Custom validators** — sync and async `custom` functions.
46
+ - **Error handling** — structured errors with field paths, custom messages, `abortEarly`.
47
+ - **Security** — prototype pollution protection, depth/size limits, immutable input.
48
+
49
+ ## API
50
+
51
+ ### `validate(schema, options?)` — Express Middleware
52
+
53
+ Returns an Express middleware function.
54
+
55
+ ```js
56
+ app.post('/register', validate(schema, options), handler);
57
+ ```
58
+
59
+ Options are validated eagerly at middleware creation time (not per-request), so configuration errors are caught during app startup.
60
+
61
+ ### `validateData(input, schema, options?)` — Standalone
62
+
63
+ Express-independent validation. Returns a `Promise<Object>`.
64
+
65
+ ```js
66
+ const { validateData } = require('valireq');
67
+
68
+ const result = await validateData(
69
+ { name: ' Prakhar ', age: '20' },
70
+ { name: { type: 'string', trim: true }, age: { type: 'number', coerce: true } }
71
+ );
72
+ // { name: 'Prakhar', age: 20 }
73
+ ```
74
+
75
+ ### `ValidationError`
76
+
77
+ Thrown when validation fails. Properties:
78
+
79
+ - `name` — `'ValidationError'`
80
+ - `message` — `'Validation failed'`
81
+ - `status` — `400`
82
+ - `errors` — `[{ field, rule, message }]`
83
+ - `toJSON()` — `{ success: false, message, errors }`
84
+
85
+ ## Validation Rules Reference
86
+
87
+ ### Basic Rules
88
+
89
+ | Rule | Type | Description |
90
+ |------|------|-------------|
91
+ | `required` | `boolean` | Field must be present (not `undefined`). Null values also trigger a required error unless `nullable` is set. |
92
+ | `nullable` | `boolean` | Allow `null` values. |
93
+ | `type` | `string` | Expected type: `'string'`, `'number'`, `'integer'`, `'boolean'`, `'array'`, `'object'`, `'date'`. |
94
+ | `enum` | `Array` | Value must be in the array (strict equality). |
95
+ | `oneOf` | `Array` | Alias for `enum`. |
96
+ | `equals` | `any` | Value must strictly equal this. |
97
+ | `notEquals` | `any` | Value must not strictly equal this. |
98
+
99
+ ### String Rules
100
+
101
+ | Rule | Type | Description |
102
+ |------|------|-------------|
103
+ | `minLength` | `number` | Minimum string length. |
104
+ | `maxLength` | `number` | Maximum string length. |
105
+ | `exactLength` | `number` | Exact string length. |
106
+ | `email` | `boolean` | Must be a valid email address. Rejects consecutive dots and requires a 2+ char TLD. |
107
+ | `url` | `boolean` | Must be a valid URL (uses `new URL()`). |
108
+ | `uuid` | `boolean` | Must be a valid UUID (v1–v5). |
109
+ | `alphanumeric` | `boolean` | Letters and digits only. |
110
+ | `numeric` | `boolean` | Numeric string (integers, decimals, negatives). |
111
+ | `alphabetic` | `boolean` | Letters only. |
112
+ | `isLowercase` | `boolean` | Must already be lowercase (validation only, does not transform). |
113
+ | `isUppercase` | `boolean` | Must already be uppercase (validation only, does not transform). |
114
+ | `startsWith` | `string` | Must start with the given prefix. |
115
+ | `endsWith` | `string` | Must end with the given suffix. |
116
+ | `contains` | `string` | Must contain the given substring. |
117
+ | `matches` | `RegExp` | Must match the regular expression. |
118
+
119
+ ### Number Rules
120
+
121
+ | Rule | Type | Description |
122
+ |------|------|-------------|
123
+ | `min` | `number` | Minimum value (inclusive). Works with `min: 0`. |
124
+ | `max` | `number` | Maximum value (inclusive). Works with `max: 0`. |
125
+ | `integer` | `boolean` | Must be an integer. |
126
+ | `positive` | `boolean` | Must be > 0. |
127
+ | `negative` | `boolean` | Must be < 0. |
128
+ | `finite` | `boolean` | Must be finite. |
129
+
130
+ ### Array Rules
131
+
132
+ | Rule | Type | Description |
133
+ |------|------|-------------|
134
+ | `items` | `object` | Schema for validating each array item. |
135
+ | `minItems` | `number` | Minimum number of items. |
136
+ | `maxItems` | `number` | Maximum number of items. |
137
+
138
+ ### Object Rules
139
+
140
+ | Rule | Type | Description |
141
+ |------|------|-------------|
142
+ | `properties` | `object` | Schema for validating object properties. When `properties` is set, the value is treated as an object even without `type: 'object'`. |
143
+
144
+ ## Sanitization
145
+
146
+ Sanitization options transform string values. They only apply when explicitly enabled.
147
+
148
+ ```js
149
+ validate({
150
+ name: { type: 'string', trim: true, removeExtraSpaces: true },
151
+ email: { type: 'string', trim: true, lowercase: true, email: true }
152
+ });
153
+ ```
154
+
155
+ | Option | Description |
156
+ |--------|-------------|
157
+ | `trim` | Remove leading/trailing whitespace. |
158
+ | `lowercase` | Convert to lowercase. **This is a sanitizer** — it transforms the value. To validate that a string is already lowercase, use `isLowercase`. |
159
+ | `uppercase` | Convert to uppercase. **This is a sanitizer** — it transforms the value. To validate that a string is already uppercase, use `isUppercase`. |
160
+ | `removeExtraSpaces` | Collapse repeated whitespace to a single space. |
161
+ | `stripHtml` | Remove HTML tags. |
162
+ | `removeNullBytes` | Remove null bytes (`\0`). |
163
+ | `normalizeEmail` | Conservative email normalization: lowercases the entire address. For Gmail/Googlemail, also removes dots and plus-addressing from the local part. |
164
+ | `escapeHtml` | Escape `&`, `<`, `>`, `"`, `'` to HTML entities. |
165
+
166
+ > **Important:** Sanitization is not a substitute for parameterized SQL queries or context-aware output encoding.
167
+
168
+ ### Order of Operations
169
+
170
+ Sanitization is applied in this order:
171
+ 1. `removeNullBytes`
172
+ 2. `trim`
173
+ 3. `removeExtraSpaces`
174
+ 4. `stripHtml`
175
+ 5. `normalizeEmail`
176
+ 6. `lowercase` / `uppercase`
177
+ 7. `escapeHtml`
178
+
179
+ ## Coercion & Transformation
180
+
181
+ ### Type Coercion
182
+
183
+ Enable with `coerce: true`. Only coerces strings.
184
+
185
+ ```js
186
+ validate({
187
+ age: { type: 'number', coerce: true }, // "20" → 20
188
+ count: { type: 'integer', coerce: true }, // "5" → 5, "3.5" → rejected
189
+ active: { type: 'boolean', coerce: true }, // "true"/"1" → true, "false"/"0" → false
190
+ when: { type: 'date', coerce: true } // "2025-01-01" → Date object
191
+ });
192
+ ```
193
+
194
+ Coercion rules:
195
+ - **Number:** Empty strings and non-numeric strings are not coerced (they remain as strings and fail the type check).
196
+ - **Integer:** Only strings representing safe integers are coerced. `"3.5"` is not coerced and fails the type check.
197
+ - **Boolean:** Only `"true"`, `"1"`, `"false"`, `"0"` are coerced.
198
+ - **Date:** Uses `new Date(value)`. Invalid dates are not coerced.
199
+
200
+ ### Default Values
201
+
202
+ ```js
203
+ validate({
204
+ role: { type: 'string', default: 'user' },
205
+ id: { type: 'string', default: () => crypto.randomUUID() },
206
+ token: { type: 'string', default: async () => await generateToken() }
207
+ });
208
+ ```
209
+
210
+ ### Custom Transforms
211
+
212
+ ```js
213
+ validate({
214
+ tags: { type: 'string', transform: value => value.split(',') }
215
+ });
216
+ ```
217
+
218
+ ## Unknown Field Handling
219
+
220
+ Control what happens to fields not defined in the schema.
221
+
222
+ ```js
223
+ validate(schema, { unknown: 'strip' }); // Default: remove unknown fields
224
+ validate(schema, { unknown: 'strict' }); // Reject requests with unknown fields
225
+ validate(schema, { unknown: 'passthrough' }); // Keep unknown fields in output
226
+ ```
227
+
228
+ Unknown field handling also applies to nested objects inside `properties`.
229
+
230
+ ## Nested Objects and Arrays
231
+
232
+ ```js
233
+ validate({
234
+ address: {
235
+ type: 'object',
236
+ properties: {
237
+ city: { required: true, type: 'string' },
238
+ pincode: { type: 'string', exactLength: 6 }
239
+ }
240
+ },
241
+ hobbies: {
242
+ type: 'array',
243
+ items: { type: 'string' },
244
+ minItems: 1,
245
+ maxItems: 10
246
+ },
247
+ users: {
248
+ type: 'array',
249
+ items: {
250
+ type: 'object',
251
+ properties: {
252
+ name: { required: true, type: 'string' },
253
+ email: { required: true, type: 'string', email: true }
254
+ }
255
+ }
256
+ }
257
+ });
258
+ ```
259
+
260
+ Error paths use dot notation for objects and bracket notation for arrays:
261
+ ```
262
+ address.pincode
263
+ hobbies[1]
264
+ users[0].email
265
+ ```
266
+
267
+ > **Tip:** Setting `properties` on a rule automatically treats the value as an object, so `type: 'object'` is optional when `properties` is present.
268
+
269
+ ## Custom Validators
270
+
271
+ ```js
272
+ validate({
273
+ username: {
274
+ required: true,
275
+ custom: (value) => value !== 'admin',
276
+ message: 'This username is not allowed.'
277
+ }
278
+ });
279
+ ```
280
+
281
+ Custom validators must return exactly `true` to pass. Any other return value (including other truthy values like `1`, `"yes"`, etc.) is treated as a validation failure.
282
+
283
+ ### Async Validators
284
+
285
+ ```js
286
+ validate({
287
+ username: {
288
+ required: true,
289
+ custom: async (value) => {
290
+ const exists = await checkDatabase(value);
291
+ return !exists;
292
+ },
293
+ message: 'Username is already taken.'
294
+ }
295
+ });
296
+ ```
297
+
298
+ Exceptions thrown inside custom validators are caught and converted to validation errors. Internal error details are never exposed to clients.
299
+
300
+ ## Empty String Handling
301
+
302
+ | Scenario | Behavior |
303
+ |----------|----------|
304
+ | Empty string, no rules | Excluded from output |
305
+ | `required: true` + empty string | Included in output (required checks for `undefined`/`null`, not empty) |
306
+ | `allowEmpty: true` | Included in output |
307
+ | `rejectEmpty: true` | Validation error |
308
+
309
+ If you need required fields to reject empty strings, combine `required: true` with `rejectEmpty: true` or `minLength: 1`.
310
+
311
+ ## Express Integration
312
+
313
+ ### Source Selection
314
+
315
+ ```js
316
+ app.post('/users', validate(schema, { source: 'body' }), handler); // Default
317
+ app.get('/search', validate(schema, { source: 'query' }), handler);
318
+ app.get('/users/:id', validate(schema, { source: 'params' }), handler);
319
+ ```
320
+
321
+ ### Output Modes
322
+
323
+ ```js
324
+ // Default: req.validated = { ... }
325
+ app.post('/users', validate(schema), handler);
326
+
327
+ // By source: req.validated.body = { ... }
328
+ app.post('/users', validate(bodySchema, { source: 'body', output: 'bySource' }), handler);
329
+ app.post('/users', validate(querySchema, { source: 'query', output: 'bySource' }), handler);
330
+ // Access: req.validated.body, req.validated.query
331
+ ```
332
+
333
+ ### Custom Error Handler
334
+
335
+ ```js
336
+ validate(schema, {
337
+ onError: (error, req, res, next) => {
338
+ res.status(422).json({ errors: error.errors });
339
+ }
340
+ });
341
+ ```
342
+
343
+ ## Configuration Options
344
+
345
+ | Option | Type | Default | Description |
346
+ |--------|------|---------|-------------|
347
+ | `source` | `string` | `'body'` | Request source: `'body'`, `'query'`, `'params'`. |
348
+ | `output` | `string` | `'validated'` | Output mode: `'validated'` or `'bySource'`. |
349
+ | `unknown` | `string` | `'strip'` | Unknown field policy: `'strip'`, `'strict'`, `'passthrough'`. |
350
+ | `abortEarly` | `boolean` | `false` | Stop validation after the first error. |
351
+ | `maxDepth` | `number` | `20` | Maximum nested object depth. |
352
+ | `maxArrayLength` | `number` | `1000` | Maximum array length (DoS protection). |
353
+ | `maxObjectKeys` | `number` | `1000` | Maximum object keys (DoS protection). |
354
+ | `onError` | `function` | — | Custom error handler `(error, req, res, next)`. |
355
+
356
+ ## Error Format
357
+
358
+ ```json
359
+ {
360
+ "success": false,
361
+ "message": "Validation failed",
362
+ "errors": [
363
+ {
364
+ "field": "email",
365
+ "message": "Must be a valid email address.",
366
+ "rule": "email"
367
+ },
368
+ {
369
+ "field": "password",
370
+ "message": "Must be at least 8 characters.",
371
+ "rule": "minLength"
372
+ }
373
+ ]
374
+ }
375
+ ```
376
+
377
+ ## Security Considerations
378
+
379
+ - **Immutability:** Output is always a newly allocated object. The original `req.body`/`req.query`/`req.params` is never modified.
380
+ - **Prototype pollution:** `__proto__`, `prototype`, and `constructor` keys are ignored in input and schema.
381
+ - **Depth protection:** Configurable `maxDepth` prevents stack overflow from deeply nested input.
382
+ - **Size limits:** `maxArrayLength` and `maxObjectKeys` prevent DoS from large payloads.
383
+ - **Date cloning:** Date objects in output are cloned to prevent mutation through shared references.
384
+ - **Object cloning:** Objects and arrays without sub-schemas are deep-cloned in output.
385
+ - **Regex safety:** Stateful regexes (with `g` flag) are reset before and after each test.
386
+ - **Error isolation:** Exceptions from custom validators and transforms are caught; internal details are never exposed.
387
+
388
+ > **Note:** Sanitization (e.g., `escapeHtml`, `stripHtml`) is not a substitute for parameterized queries or context-aware output encoding. Application-supplied regular expressions should be reviewed for worst-case behavior.
389
+
390
+ ## Limitations
391
+
392
+ - `lowercase`/`uppercase` are sanitizers (they transform the value). Use `isLowercase`/`isUppercase` for validation-only checks.
393
+ - UUID validation covers v1–v5 only (not v6/v7/v8 from RFC 9562).
394
+ - Email validation is intentionally basic — it checks format, rejects consecutive dots, and requires a 2+ char TLD, but does not fully validate per RFC 5322.
395
+ - Date coercion relies on the JavaScript `Date` constructor, which has platform-specific edge cases.
396
+ - `cloneInput` handles `Date`, `Array`, and plain objects. `RegExp`, `Map`, `Set`, `Buffer`, and other types are returned by reference (these are rare in JSON-parsed request bodies).
397
+
398
+ ## Development
399
+
400
+ ```sh
401
+ npm test # Run all tests (Node.js built-in test runner)
402
+ npm run lint # Syntax check
403
+ npm pack --dry-run # Preview npm package contents
404
+ ```
405
+
406
+ No Express dependency is bundled; install it in the consuming application. Node.js 18+ and CommonJS are required.
407
+
408
+ ## License
409
+
410
+ MIT
@@ -0,0 +1,81 @@
1
+ /**
2
+ * ValiReq — Basic Express Middleware Example
3
+ *
4
+ * Demonstrates:
5
+ * - Required fields
6
+ * - Type checking and coercion
7
+ * - Sanitization (trim, lowercase)
8
+ * - Email validation
9
+ * - Default values
10
+ * - Unknown-field stripping (enabled by default)
11
+ *
12
+ * Run:
13
+ * npm install express
14
+ * node examples/basic.js
15
+ *
16
+ * Test with curl:
17
+ * curl -X POST http://localhost:3000/register \
18
+ * -H 'Content-Type: application/json' \
19
+ * -d '{"email":" TEST@Example.COM ","password":"secret1234","age":"25","extra":"stripped"}'
20
+ */
21
+
22
+ const express = require('express');
23
+ const { validate } = require('../src');
24
+
25
+ const app = express();
26
+ app.use(express.json());
27
+
28
+ const registerSchema = {
29
+ email: {
30
+ required: true,
31
+ type: 'string',
32
+ email: true,
33
+ trim: true,
34
+ lowercase: true,
35
+ },
36
+
37
+ password: {
38
+ required: true,
39
+ type: 'string',
40
+ minLength: 8,
41
+ maxLength: 64,
42
+ },
43
+
44
+ age: {
45
+ type: 'number',
46
+ coerce: true,
47
+ min: 18,
48
+ },
49
+
50
+ role: {
51
+ type: 'string',
52
+ enum: ['user', 'admin'],
53
+ default: 'user',
54
+ },
55
+ };
56
+
57
+ app.post('/register', validate(registerSchema), (req, res) => {
58
+ // req.validated contains only the declared fields, sanitized and coerced.
59
+ // Unknown fields (like "extra") are automatically stripped.
60
+ res.json({ success: true, data: req.validated });
61
+ });
62
+
63
+ // Query parameter validation
64
+ app.get(
65
+ '/search',
66
+ validate(
67
+ {
68
+ q: { required: true, type: 'string', trim: true, minLength: 1 },
69
+ page: { type: 'integer', coerce: true, min: 1, default: 1 },
70
+ limit: { type: 'integer', coerce: true, min: 1, max: 100, default: 20 },
71
+ },
72
+ { source: 'query' },
73
+ ),
74
+ (req, res) => {
75
+ res.json({ success: true, data: req.validated });
76
+ },
77
+ );
78
+
79
+ app.listen(3000, () => {
80
+ console.log('Server running on http://localhost:3000');
81
+ });
@@ -0,0 +1,136 @@
1
+ /**
2
+ * ValiReq — Custom Validation Example
3
+ *
4
+ * Demonstrates:
5
+ * - Synchronous custom validators
6
+ * - Asynchronous custom validators
7
+ * - Custom error messages
8
+ * - Custom transforms
9
+ * - Custom onError handler (middleware)
10
+ *
11
+ * Run:
12
+ * node examples/custom-validation.js
13
+ */
14
+
15
+ const { validateData, validate, ValidationError } = require('../src');
16
+
17
+ async function main() {
18
+ // ── Sync custom validator ──
19
+ console.log('--- Sync custom validator ---');
20
+
21
+ try {
22
+ await validateData(
23
+ { username: 'admin' },
24
+ {
25
+ username: {
26
+ required: true,
27
+ type: 'string',
28
+ custom: (value) => value !== 'admin',
29
+ message: 'This username is not allowed.',
30
+ },
31
+ },
32
+ );
33
+ } catch (error) {
34
+ console.log('Error:', error.errors[0].message);
35
+ // Error: This username is not allowed.
36
+ }
37
+
38
+ // ── Async custom validator ──
39
+ console.log('\n--- Async custom validator ---');
40
+
41
+ // Simulates a database check.
42
+ const takenUsernames = new Set(['alice', 'bob']);
43
+
44
+ const result = await validateData(
45
+ { username: 'prakhar' },
46
+ {
47
+ username: {
48
+ required: true,
49
+ type: 'string',
50
+ isLowercase: true,
51
+ minLength: 3,
52
+ maxLength: 20,
53
+ custom: async (value) => {
54
+ // Simulate async DB lookup.
55
+ await new Promise((resolve) => setTimeout(resolve, 10));
56
+ return !takenUsernames.has(value);
57
+ },
58
+ message: 'Username is already taken.',
59
+ },
60
+ },
61
+ );
62
+
63
+ console.log('Valid username:', result.username);
64
+
65
+ // ── Custom validators must return exactly `true` ──
66
+ console.log('\n--- Custom validators must return true ---');
67
+
68
+ try {
69
+ await validateData(
70
+ { count: 5 },
71
+ {
72
+ count: {
73
+ // Returns 5 (truthy but not `true`), so this FAILS.
74
+ custom: (value) => value,
75
+ message: 'Custom must return exactly true, not just a truthy value.',
76
+ },
77
+ },
78
+ );
79
+ } catch (error) {
80
+ console.log('Error:', error.errors[0].message);
81
+ }
82
+
83
+ // Fix: return a boolean comparison instead.
84
+ const fixed = await validateData(
85
+ { count: 5 },
86
+ {
87
+ count: {
88
+ custom: (value) => value > 0, // Returns true.
89
+ },
90
+ },
91
+ );
92
+ console.log('Fixed result:', fixed.count);
93
+
94
+ // ── Custom transform ──
95
+ console.log('\n--- Custom transform ---');
96
+
97
+ const transformed = await validateData(
98
+ { tags: 'js,node,express' },
99
+ {
100
+ tags: {
101
+ // No type constraint here — the transform converts a string to an array.
102
+ transform: (value) =>
103
+ typeof value === 'string'
104
+ ? value.split(',').map((s) => s.trim())
105
+ : value,
106
+ },
107
+ },
108
+ );
109
+
110
+ console.log('Transformed tags:', transformed.tags);
111
+ // Transformed tags: ['js', 'node', 'express']
112
+
113
+ // ── Validator exception handling ──
114
+ console.log('\n--- Validator exception handling ---');
115
+
116
+ try {
117
+ await validateData(
118
+ { value: 'test' },
119
+ {
120
+ value: {
121
+ custom: () => {
122
+ throw new Error('Internal DB connection failed');
123
+ },
124
+ },
125
+ },
126
+ );
127
+ } catch (error) {
128
+ // Internal details are never exposed to clients.
129
+ console.log('Error message:', error.errors[0].message);
130
+ console.log('Contains internal detail?', error.errors[0].message.includes('DB'));
131
+ // Error message: Validation failed.
132
+ // Contains internal detail? false
133
+ }
134
+ }
135
+
136
+ main().catch(console.error);