-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathschemas.ts
54 lines (50 loc) · 1.26 KB
/
schemas.ts
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
import { z } from 'zod';
/**
* Zod schema to parse strings that are booleans.
* Use to parse <input type="hidden" value="true" /> values.
* @example
* ```ts
* BoolAsString.parse('true') -> true
* ```
*/
export const BoolAsString = z
.string()
.regex(/^(true|false)$/, 'Must be a boolean string ("true" or "false")')
.transform((value) => value === 'true');
/**
* Zod schema to parse checkbox formdata.
* Use to parse <input type="checkbox" /> values.
* @example
* ```ts
* CheckboxAsString.parse('on') -> true
* CheckboxAsString.parse(undefined) -> false
* ```
*/
export const CheckboxAsString = z
.literal('on')
.optional()
.transform((value) => value === 'on');
/**
* Zod schema to parse strings that are integers.
* Use to parse <input type="number" /> values.
* @example
* ```ts
* IntAsString.parse('3') -> 3
* ```
*/
export const IntAsString = z
.string()
.regex(/^-?\d+$/, 'Must be an integer string')
.transform((val) => parseInt(val, 10));
/**
* Zod schema to parse strings that are numbers.
* Use to parse <input type="number" step="0.1" /> values.
* @example
* ```ts
* NumAsString.parse('3.14') -> 3.14
* ```
*/
export const NumAsString = z
.string()
.regex(/^-?\d*\.?\d+$/, 'Must be a number string')
.transform(Number);