1const Joi = require('@hapi/joi');
2
3const joiSchema = Joi.object({
4 a: Joi.string()
5 .min(2)
6 .max(10)
7 .required()
8 .messages({
9 'string.base': `"a" should be a type of 'text'`,
10 'string.empty': `"a" cannot be an empty field`,
11 'string.min': `"a" should have a minimum length of {#limit}`,
12 'any.required': `"a" is a required field`
13 })
14});
15
16const validationResult = joiSchema.validate({ a: 2 }, { abortEarly: false });
17console.log(validationResult.error); // expecting ValidationError: "a" should be a type of 'text'
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) { }
1Joi.object().keys({
2 contact: Joi.object().keys({
3 first_name: Joi.string(),
4 last_name: Joi.string(),
5 phone: Joi.string(),
6 }),
7 address: Joi.object().keys({
8 place: Joi.string(),
9 city: Joi.string().min(2).max(30),
10 street: Joi.string(),
11 house_number: Joi.string()
12 }).when('contact', {
13 is: Joi.object().keys({
14 first_name: Joi.exist(),
15 last_name: Joi.exist(),
16 phone: Joi.exist(),
17 }),
18 then: Joi.object({ place: Joi.required() }).required(),
19 otherwise: Joi.object({ place: Joi.forbidden() })
20 }),
21 passengers_amount: Joi.number(),
22 notes: Joi.string()
23});
24
1const joi = require("joi");
2
3const validation = joi.object({
4 userName: joi.string().alphanum().min(3).max(25).trim(true).required(),
5 email: joi.string().email().trim(true).required(),
6 password: joi.string().min(8).trim(true).required(),
7 mobileNumber: joi.string().length(10).pattern(/[6-9]{1}[0-9]{9}/).required(),
8 birthYear: joi.number().integer().min(1920).max(2000),
9 skillSet: joi.array().items(joi.string().alphanum().trim(true)).default([]),
10 is_active: joi.boolean().default(true),
11});
12
1function responseValidate(response) {
2 const schema = {
3 id: Joi.objectId().required(),
4 response: Joi.string().min(3).max(512).required()
5 };
6
7 return schema.validate(response);
8}
9