'Extracting a type and constraint from a Joi schema

If I have a schema:

const schema = Joi.object({
    title: Joi.string().trim().alphanum().min(3).max(50).required().messages({
        "string.base": `Must be text`,
        "string.empty": `Cannot be empty`,
        "string.min": `Must be > 3`,
        "string.max": `Must be < than 50`,
        "any.required": `Required`,
    }),

    ... // more key/constraints 
});

Is it possible to access the key/value pair of the Joi object in order to use it in a function to validate an individual field?

So for example I could do something like this:

const validateProperty = ({ value, name }, schema) => {
    const { error } = schema[name].validate(value);
    if(!error) return null;
    return error.details[0].message;
};

validateProperty({value:valueToValidate, name:'title'}, schema)

where name is the key of the constraint in the schema? It would just save me writing a schema for an entire form, and then rewriting each individual constraint as its own schema in order to validate individual fields when needed (for example onBlur)



Solution 1:[1]

Turns out .extract() here was the correct answer, it was just a bug in my implementation:

const validateProperty = ({ value, name }, schema) => {
    const { error } = schema.extract(name).validate(value);
    if(!error) return null;
    return error.details[0].message;
};

const validate = (data, schema) => {
    const options = { abortEarly: false }
    const { error } = schema.validate(data, options);
    if(!error) return null;

    const errors = {};
    error.details.forEach(error => {
      errors[error.path[0]] = error.message
    })
    return errors;
}

validate(data, schema)

validateProperty({ value: valueToValidate, schema })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NickW