How to use the validate function from joi

Find comprehensive JavaScript joi.validate code examples handpicked from public code repositorys.

14
15
16
17
18
19
20
21
22
23
try {
        const reqParam = req.params.id;
        const schema = {
                id: Joi.number().integer().min(1),
        };
        const { error } = Joi.validate({ id: reqParam }, schema);
        requestHandler.validateJoi(error, 400, 'bad Request', 'invalid User Id');

        const result = await super.getById(req, 'Users');
        return requestHandler.sendSuccess(res, 'User Data Extracted')({ result });
fork icon114
star icon404
watch icon13

172
173
174
175
176
177
178
179
180
181
let legacy = false;

Object.keys(manifestSchema).forEach(function (key) {
  const schema = manifestSchema[key];
  const value = inputManifest[key];
  const result = joi.validate(value, schema);
  if (result.error) {
    if (key === '$schema') {
      manifest[key] = CANONICAL_SCHEMA;
      console.warnLines(il`
fork icon816
star icon0
watch icon338

14
15
16
17
18
19
20
21
22
23
return get(schemaUri, { rejectUnauthorized: false })
    .spread(function (res, schemaPayload) {
        if (res.statusCode !== 200) return Bluebird.reject(Boom.serverTimeout(MISSING_SCHEMA_ERROR))
        if (!flatmarketSchema.isValid(schemaPayload)) return Bluebird.reject(Boom.serverTimeout(INVALID_SCHEMA_ERROR))
        if (!isValidRequest(schemaPayload, payload)) return Bluebird.reject(Boom.badRequest())
        var schema = Joi.validate(schemaPayload, flatmarketSchema).value
        var sku = schema.products[payload.sku]
        var stripePayload = {
            metadata: _.chain(payload.metadata)
                .omit([
fork icon133
star icon988
watch icon32

57
58
59
60
61
62
63
64
65
66
// 同步读取所有json文件
sitePaths.forEach((sitePath) => {
    const siteData = fs.readJsonSync(sitePath);

    Object.keys(siteData).forEach((key) => {
        Joi.validate(siteData[key], siteSchema, (error) => {
            if (error) {
                errorList.push(new Error(`[SITE] ${path.relative(SITES_DIRECTORY, sitePath)} ${key}: ${error.message}`));
            }
        });
fork icon58
star icon428
watch icon17

+ 3 other calls in file

6
7
8
9
10
11
12
13
14
15
const Joi = require('joi')

describe('dashboard/schema', () => {
  context('Parse', () => {
    it('Throws on invalid schema', () => {
      const { error } = Joi.validate({}, schema)
      expect(error.message).to.include('"layout" is required')
    })

    const dashboardsDir = join(__dirname, '..', '..', '..', 'dashboards')
fork icon47
star icon410
watch icon0

+ 95 other calls in file

100
101
102
103
104
105
106
107
108
        email: Joi.string().email().required(),
        name: Joi.string().required(),
};
const randomString = stringUtil.generateString();

const { error } = Joi.validate({ email: data.email, name: data.name }, schema);
requestHandler.validateJoi(error, 400, 'bad Request', error ? error.details[0].message : '');
const options = { where: { email: data.email } };
const user = await super.getByCustomOptions(req, 'Users', options);
fork icon114
star icon403
watch icon13

+ 7 other calls in file

51
52
53
54
55
56
57
58
59
 * @param {Object} schema
 * @param {Object} config
 */

BaseDecorator.prototype._validateConfig = function (schema, config) {
  var validation = joi.validate(config, schema);
  if (validation.error) throw validation.error;
  return validation.value;
};
fork icon4
star icon54
watch icon29

+ 3 other calls in file

76
77
78
79
80
81
82
83
84
85
 * @param next
 */
exports.register = function (server, opts, next) {
    var settings = opts;

    joi.validate(opts, optionsSchema, function (err, validated) {
        if (err) throw err;

        settings = validated;
    });
fork icon23
star icon0
watch icon1

+ 11 other calls in file

66
67
68
69
70
71
72
73
74
75
}

async _validate_with_validator(method: string, object: Object, errors: Object,
    validator: Function, key: ?string): Object {
    if (Validator._isJoi(validator)) {
        const val = Joi.validate(object, validator, this._options.joi);
        if (val.error) {
            Validator._compose_joi_errors(errors, val.error, key);
        }
    } else {
fork icon10
star icon26
watch icon15

21
22
23
24
25
26
27
28
29
30
  password: Joi.string()
    .min(5)
    .required()
}

const { error } = Joi.validate(req.body, schema)

if (error) {
  return res.status(400).send({
    success: false,
fork icon2
star icon23
watch icon3

+ 3 other calls in file

177
178
179
180
181
182
183
184
185
    .falsy('false')
    .default(true)
}).unknown()
  .required()

const { error, value: envVars } = joi.validate(process.env, envVarsSchema)  
if (error) {  
  throw new Error(`Config validation error: ${error.message}`)
}
fork icon5
star icon22
watch icon3

118
119
120
121
122
123
124
125
126
127
 * Validates a driver in a before/after sandwich and returns the validated driver
 * @param driver
 * @returns {*}
 */
validate (driver) {
    joi.validate(this.beforeValidate(driver) || driver, this.schema, this.options, (err, validated) => {
        if (err) throw err;
        driver = validated;
    });
    this.afterValidate(driver);
fork icon2
star icon0
watch icon2

29
30
31
32
33
34
35
36
37
38
    username: Joi.string().min(3).required(),
    password: Joi.string().min(3).required(),
    confpassword: Joi.string().min(3).required(),
};

const result = Joi.validate(req.body, schema);
if(result.error){
    res.render('register', {
        errors: result.error.details[0].message
    });
fork icon1
star icon4
watch icon2

36
37
38
39
40
41
42
43
44
45
function validate(req){
    const schema = {
        email: Joi.string().min(5).max(255).required().email(),
        password: Joi.string().min(8).max(255).required()
    }
    return Joi.validate(req, schema);
}


module.exports = router;
fork icon0
star icon2
watch icon1

57
58
59
60
61
62
63
64
65
   

});

// validate the request data against the schema
Joi.validate(data, schema, (err, value) => {

    // create a random number as id
    //const id = Math.ceil(Math.random() * 9999999);
fork icon0
star icon0
watch icon1

+ 7 other calls in file

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38






router.delete('/', async (req, res) => {
  const UploadSchema = { images: Joi.array().items(Joi.string(), Joi.string()) }
  const { error } = Joi.validate(req.body, UploadSchema);


  if (error) return res.status(400).send({ "message": error.details[0].message.replace(/['"]+/g, '') });


  await req.body.images.map(value => { S3delete(value, (err, value) => { }) })
fork icon0
star icon0
watch icon1

79
80
81
82
83
84
85
86
87
88
    password: Joi.string()
      .min(8)
      .max(255)
      .required()
  };
  return Joi.validate(user, schema, { allowUnknown: false });
};
validateUserUpdate = user => {
  const schema = {
    name: Joi.string()
fork icon0
star icon0
watch icon1

157
158
159
160
161
162
163
164
165
166
167
168
        email: Joi.string().min(1).max(64).email().required(),
        password: Joi.string().min(1).max(128).required(),
        rid: Joi.number()
    };


    return Joi.validate(employee, schema);
}


// put validator
function validatePut(employee) {
fork icon0
star icon0
watch icon1

+ 5 other calls in file

17
18
19
20
21
22
23
24
25
26
Joi.validate(value, schema, (err, value) => { });
// err -> null
// value.a -> 123 (number, not string)

// or
const result = Joi.validate(value, schema);
// result.error -> null
// result.value -> { "a" : 123 }

// or
fork icon0
star icon0
watch icon0

+ 3 other calls in file

216
217
218
219
220
221
222
223
224
Joi.validate(value, schema, function (err, value) { });
// err -> null
// value.a -> 123 (number, not string)

// or
var result = Joi.validate(value, schema);
// result.error -> null
// result.value -> { "a" : 123 }
```
fork icon0
star icon0
watch icon2