Home > Net >  Extracting a type and constraint from a Joi schema
Extracting a type and constraint from a Joi schema

Time:05-25

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)

CodePudding user response:

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 })

  • Related