joi validation required

Solutions on MaxInterview for joi validation required by the best coders in the world

showing results for - "joi validation required"
Gianluca
27 Sep 2018
1const Joi = require('joi');
2
3const schema = Joi.object({
4    username: Joi.string()
5        .alphanum()
6        .min(3)
7        .max(30)
8        .required(),
9
10    password: Joi.string()
11        .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
12
13    repeat_password: Joi.ref('password'),
14
15    access_token: [
16        Joi.string(),
17        Joi.number()
18    ],
19
20    birth_year: Joi.number()
21        .integer()
22        .min(1900)
23        .max(2013),
24
25    email: Joi.string()
26        .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
27})
28    .with('username', 'birth_year')
29    .xor('password', 'access_token')
30    .with('password', 'repeat_password');
31
32
33schema.validate({ username: 'abc', birth_year: 1994 });
34// -> { value: { username: 'abc', birth_year: 1994 } }
35
36schema.validate({});
37// -> { value: {}, error: '"username" is required' }
38
39// Also -
40
41try {
42    const value = await schema.validateAsync({ username: 'abc', birth_year: 1994 });
43}
44catch (err) { }