PIKP
PIKP

Reputation: 843

Generating Joi validation a Sequelize model

I have developed an API using expressjs and Sequelize is the ORM I have used. I want to integrate express-validation to my API to validate the request body and params. The express-validation framework uses the Joi validation rules. But as I have already defined the validation rules in my Sequalize model, I' don't like to redefine validation rules using Joi for request body validations.

I'm just wondering if there's any method or library to generate Joi validation rules based on validations defined in Sequelize model. Else, what would be the best approach to handle this?

Upvotes: 2

Views: 4733

Answers (2)

Kshitiz Koirala
Kshitiz Koirala

Reputation: 51

This question is too old however this answer maybe helpful for those newbies who are learning the language or maybe started working with sequelize

Sequelize provides validation by default. You can look into the docs

Sequelize Validation docs

However if you want to provide your own custom validators with custom "pretty" messages. You can always use the

@hapi/joi

package the "normal" way. joi-sequelize or sequelize-joi are not required just to provide custom error message.(period)


function validateData(datas) {
    const schema = Joi.object({
        user_name: Joi.string().min(3).required(),
        user_address: Joi.string().required()
    });
    return schema.validate(datas);
}

and then validate the data using

    const { error } = validateData(req.body);

which catches if any properties fails the validation.

Upvotes: 3

Mat
Mat

Reputation: 1101

Have you checked out joi-sequelize ?

Upvotes: 2

Related Questions