简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM