Yup: How to validate a subset of a schema?

Created on 28 Dec 2016  路  2Comments  路  Source: jquense/yup

Let's say I just wanted to validate the name object of this schema:

formModelSchema = yup.object({
        name: yup.object({
            first: yup.string().min(1).required('First name is required'),
            middle: yup.string(),
            last: yup.string().min(1).required('Last name is required')
        }).required('Full name is required'),
        email: yup.string().email().required('E-mail input is required')
    });

Something like this:

        console.log(this.formModelSchema.isValid({name: formValuesObject.name}).then(
            valid => console.log(valid)));

or

        console.log(this.formModelSchema.name.isValid(formValuesObject.name).then(
            valid => console.log(valid)));

But the above doesn't work. Is there a way to do this?

Most helpful comment

yes there is! you want the reach util:

yup.reach(schema, 'name').isValid(name)
yup.reach(schema, 'name.first').isValid(firstName)

All 2 comments

yes there is! you want the reach util:

yup.reach(schema, 'name').isValid(name)
yup.reach(schema, 'name.first').isValid(firstName)

@jquense can you please provide a complete example on this. I am getting stuck on this. I want to have a fullName field on my form, which will take at least firstName and lastName. In other words, the string I get on validating fullName can be split to an array of length 2 (if first name and last name only) or an array of length 3 (if first name, middle name, and last name).

Was this page helpful?
0 / 5 - 0 ratings