Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
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)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda