-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.js
89 lines (78 loc) · 2.08 KB
/
example.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
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
//import ElValidator from 'elvalidator';
import ElValidator from './index.js';
// Set up the validator object
let validator = new ElValidator({
name : { type: String, required:true, trim:true, minLength:3 },
age : { type: Number, required:true, integer:true, min:18, max:100 },
agreedTelemetry : { type: Boolean, default:false },
// Array example:
tags : [
{ type: String, minLength:3, lowercase:true, trim:true, match: /^[a-z0-9]+$/ }
],
// Object example:
settings : {
darkMode : { type: Boolean, required: true, },
codeEditor : { type: String, default:'atom', enum:['atom', 'vstudio', 'notepad++'] },
extras : { type: Object, required:true, }
},
stringOrBool : {
$or : [
{ type: String },
{ type: Boolean },
]
},
arrayWithOptions : {
type : [
{ type: String, minLength:3, lowercase:true, trim:true, match: /^[a-z0-9]+$/ }
],
minEntries : 0,
maxEntries : 20,
uniqueValues : true,
},
custom : { type: String, validator: async (value) => {
if(value.length%2 == 1)
throw new Error('The number of characters must be odd.');
return '->'+value;
}},
}, {
strictMode : true,
throwUnkownFields : false,
accumulateErrors : false,
dismissEmptyObjects : true,
});
// Validate/Sanitize a data object
var sanitizedData = await validator.validate({
name : 'Yassine',
age : 27,
tags : ['programmer', 'javascript'],
settings : {
darkMode : false,
//codeEditor : 'atom',
extras : {
one : '1',
two : 'anything',
}
},
other : 'unknown field',
stringOrBool : false,
arrayWithOptions : ['hello', 'world', 'tag', 'WillDownCase', 'TAG', 'last'],
custom : 'node'
});
console.log(sanitizedData);
/*
OUTPUT:
{
name: 'Yassine',
age: 27,
agreedTelemetry: false,
tags: [ 'programmer', 'javascript' ],
settings: {
darkMode: false,
codeEditor: 'atom',
extras: { one: '1', two: 'anything' }
},
stringOrBool: false,
arrayWithOptions: [ 'hello', 'world', 'tag', 'willdowncase', 'last' ],
custom: '->node'
}
*/