forked from ianstormtaylor/superstruct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom-types.js
43 lines (38 loc) · 895 Bytes
/
custom-types.js
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
import { superstruct } from 'superstruct'
import isEmail from 'is-email'
import isUuid from 'is-uuid'
import isUrl from 'is-url'
// Define a `struct` with custom types.
const struct = superstruct({
types: {
uuid: v => isUuid.v4(v),
email: v => {
if (!isEmail(v)) return `not_email`
if (v.length >= 256) return 'too_long'
return true
},
url: v => isUrl(v) && v.length < 2048,
},
})
// Define a struct to validate with.
const User = struct({
id: 'uuid',
name: 'string',
email: 'email',
website: 'url?',
})
// Define data to be validated.
const data = {
id: 'c8d63140-a1f7-45e0-bfc6-df72973fea86',
name: 'Jane Smith',
email: '[email protected]',
website: 'https://jane.example.com',
}
// Validate the data. In this case, the data is valid, so it won't throw.
try {
User(data)
console.log('Valid!')
} catch (e) {
throw e
}
// 'Valid!'