koa2-validation icon indicating copy to clipboard operation
koa2-validation copied to clipboard

Allow custom validation rules

Open djbingham opened this issue 6 years ago • 1 comments

Hi,

Joi enables custom validation to be implemented using extensions, which create a modified Joi instance. However, because koa2-validation requires Joi directly and extensions do not modify the original Joi instance, it currently doesn't seem possible to use custom Joi extensions with koa2-validation.

I think a solution would be to wrap the main validate function in a factory function which accepts a Joi instance as an argument:

# lib/index.js
const VanillaJoi = require('joi');

module.exports = (Joi = VanillaJoi) => (schema = {}) => {
    ...
};

We could then load the validate function with an extended Joi instance as follows:

const Joi = require('joi');
const myJoi = Joi.extend((joi) => {...});
const validate = require('koa2-validation')(myJoi);

Unfortunately, that is a breaking change as there's the additional function call required. I'm not sure how to determine whether something is a root Joi instance or a schema, but if there is a way then I think something like the following should be backwards-compatible:

# lib/index.js
const VanillaJoi = require('joi');

const validate = (Joi) => (schema = {}) => {
    ...
};

module.exports = (JoiOrSchema = {}) => {
    if (typeof JoiOrSchema === 'object') { # change this to account for Joi schema instances too
        return validate(VanillaJoi)(JoiOrSchema);
    } else {
        return validate(JoiOrSchema);
    }
};

djbingham avatar Mar 22 '18 18:03 djbingham

@djbingham Thx for ur advice, David, that sounds great。I will follow up the new feature soon。Or maybe u can post a pull request with enough tests, and I will appreciate for it.

molinjun avatar Mar 28 '18 00:03 molinjun