This could be implemented outside of the core, but it would be nice to have a standard JSON format to create joi schemas on the fly.
Use case:
Say a client wants to define a new data type with validation. JSON interpretation would allow both the data and the schema to be saved in the db.
Sounds like a fun project. I agree it doesn't belong in joi itself. I don't have any use cases for this but if someone comes with one, I'm happy to reopen the issue.
If anyone stumbles across this, I have the exact same use case as OP describes. I have solved it using eval - granted - not pretty, but works very well.
const schemaObject = {};
if (type === 'string' ) {
joiSchemaDescription += 'Joi.string()';
if (min_length) {
joiSchemaDescription += '.min(min_length)';
}
if (max_length) {
joiSchemaDescription += '.max(max_length)';
}
if (required) {
joiSchemaDescription += '.required()';
}
schemaObject[name] = eval(`${joiSchemaDescription};`);
}
// 'name' is also provided by the user, so you end up with a nice custom Schema like:
// schemaObject = {
// someName: Joi.string().min(5).required(),
// someOtherName: Joi.number().required();
// };
// Then validate like this:
// const fullSchema = Joi.object().keys(schemaObject);
// const validation = Joi.validate(data, fullSchema);
If anyone stumbles across this, I have the exact same use case as OP describes. I have solved it using
eval- granted - not pretty, but works very well.const schemaObject = {}; if (type === 'string' ) { joiSchemaDescription += 'Joi.string()'; if (min_length) { joiSchemaDescription += '.min(min_length)'; } if (max_length) { joiSchemaDescription += '.max(max_length)'; } if (required) { joiSchemaDescription += '.required()'; } schemaObject[name] = eval(`${joiSchemaDescription};`); } // 'name' is also provided by the user, so you end up with a nice custom Schema like: // schemaObject = { // someName: Joi.string().min(5).required(), // someOtherName: Joi.number().required(); // }; // Then validate like this: // const fullSchema = Joi.object().keys(schemaObject); // const validation = Joi.validate(data, fullSchema);
Why we need eval (evil) here? Joi is chainable.
@hueniverse I'd like to pick this back up, how best to go about it? A new project? A PR?
Thanks!
See #1867
This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.
Most helpful comment
See #1867