Reputation: 21
I'm working through a project to learn to use the Joi library within react. The instructor is using an older, deprecated, version of the library so I'm working on converting the instructors version to use the new syntax. I need to pass a Joi object for the schema and have that object call validate with the object I'm validating against as the first argument.
I'm having trouble figuring out how to dynamically call the value of the Joi object to pass into the new schema.
Here is my code as it currently stands using Joi v16
schema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.required()
.label("Username"),
password: Joi.string()
.min(5)
.required()
.label("Password")
});
validateProperty = ({ name, value }) => {
const obj = { [name]: value };
const localSchema = Joi.object({ [name]: "" }); //The copied schema segment goes here in place of the empty string.
const { error } = localSchema.validate(obj);
return error ? error.details[0].message : null;
};
My gut reaction is this "feels" wrong, like I should be doing this in a far simpler way... but I'm not sure what to do in order to move forward.
For comparison here is the instructors example written in Joi v13.
validateProperty = ({ name, value }) => {
const obj = { [name]: value };
const schema = { [name]: this.schema[name] };
Joi.validate(obj, schema);
return error ? error.details[0].message : null;
};
Upvotes: 0
Views: 1527
Reputation: 1
schemaMap = {
username: Joi.string()
.alphanum()
.min(3)
.required()
.label("Username"),
password: Joi.string()
.min(5)
.required()
.label("Password")
};
schema = Joi.object(this.schemaMap)
validateProperty = ({ name, value }) => {
const obj = { [name]: value };
const localSchema = Joi.object({ [name]: this.schemaMap[name] });
const { error } = localSchema.validate(obj);
return error ? error.details[0].message : null;
};
Upvotes: 0
Reputation: 21
Nevermind, found the answer myself!
Instead of declaring my schema as a Joi.object to begin with, I declared it as a standard JS object. Then, in my method I create a local constant that filters it THEN wraps it into a Joi.object and proceeds to validate.
schema = {
username: Joi.string()
.alphanum()
.min(3)
.required()
.label("Username"),
password: Joi.string()
.min(5)
.required()
.label("Password")
};
validateProperty = ({ name, value }) => {
const obj = { [name]: value };
const localSchema = Joi.object({ [name]: this.schema[name] });
const { error } = localSchema.validate(obj);
return error ? error.details[0].message : null;
};
Upvotes: 1