简体   繁体   中英

Validate only one single field of a bigger Joi schema

I want to use Joi for form field validation and want to stick with one big schema object for validation of the whole form, yet I want to run single entry validation after one form field has been changed - ie after the first form field has recieved a value, I do not want to validate the complete form, but only the one field updated. I am envisioning something like

const schema = Joi.object({
    username: Joi.string()
        .alphanum()
        .min(3)
        .max(30)
        .required(),

    password: Joi.string()
        .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$'))
        .required(),
});
const validationResult = schema.username.validate('Tommy');

Is that possible?

Yes, by extracting the username schema to a separate schema like so:

const username_schema = Joi.string()
        .alphanum()
        .min(3)
        .max(30)
        .required();

const schema = Joi.object({
    username: username_schema,
    password: Joi.string()
        .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$'))
        .required(),
});

const validationResult = username_schema.validate('Tommy');

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