question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Nested object validation with when not working properly.

See original GitHub issue

When i’m trying to validate a nested object. within when, it is not validating the request properly.

const updateRecord = Yup.object().shape({
	title: Yup.string()
		.required()
		.label("Post title"),
	description: Yup.string()
		.required()
		.label("Post description"),
	is_update: Yup.boolean()
		.default(false)
		.required(),
	images: Yup.object().shape({
		logoImage: Yup.mixed().when("is_update", {
			is: true,
			then: Yup.mixed()
				.nullable()
				.test("fileFormat", "Only .png file allowed.", value => {
					if (!value) {
						return true;
					}
					return value && ["image/png"].includes(value.type);
				})
				.label("Logo image"),
			otherwise: Yup.mixed()
				.required()
				.test("fileFormat", "Only .png file allowed.", value => {
					if (!value) {
						return true;
					}
					return value && ["image/png"].includes(value.type);
				})
				.label("Logo image")
		}),
		backgroundImage: Yup.mixed().when("is_update", {
			is: true,
			then: Yup.mixed()
				.nullable()
				.test("fileFormat", "Only .png file allowed.", value => {
					if (!value) {
						return true;
					}
					return value && ["image/png"].includes(value.type);
				})
				.label("Background image"),
			otherwise: Yup.mixed()
				.required()
				.test("fileFormat", "Only .png file allowed.", value => {
					if (!value) {
						return true;
					}
					return value && ["image/png"].includes(value.type);
				})
				.label("Background image")
		})
	})
});

Here i’m validating form based on is_update key which can be either true or false. but I’m getting it undefined. i have tried to console using this.

is: value => {
	console.log(value);
	return true;
}

It is logging is_update as undefined.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:30
  • Comments:16 (4 by maintainers)

github_iconTop GitHub Comments

13reactions
kentakozukacommented, Jul 6, 2021

Those who encountered this issue, check from.

yup.string()
  .test('name', 'errorMessage', function(value) {
    const { from } = this;
    // 'from' will contain the ancestor tree. You can access like from[1], from[2].
})
13reactions
ShakinFirecommented, Jan 14, 2020

A workaround I found is to use Yup.mixed.test()

Example

Yup.object<any>().shape({
    name: Yup.string(),
    gender: Yup.boolean(),
    car: Yup.object<any>().shape({
        model: Yup.string(),
        horsePower: Yup.number(),
        color: Yup.mixed().test(
            'testName',
            'My error message',
            function (this: TestContext, fieldValue: any): boolean {
                const objectToValidate = this.options.context.data; // This is the whole object that comes to the validation
                /*
                    Looks like this
                    {
                        name: 'nameToValidate',
                        gender: true,
                        car: {
                            model: 'Ford',
                            horsePower: 225,
                            color: 'red',
                        }
                    }
                */

                // Now you can take the property you need
                // and continue by custom validating it and returning 'true'
                // when it passes or 'false' when it fails
            },
        ),
    }),
});

Also, good to note that instead of false you can return this.createError({ message: "YourCustomErrorMessage" }); if you have different failures in the test.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cascaded bean validation 2.0 not working with nested object ...
Solution: I've updated my code snippets and my repository with working code examples. All I have to do is to annotate my controller...
Read more >
Validating nested objects with class-validator in NestJS
I'm using class-validator for request validation in NestJS really often. A few days ago I needed to validate a nested object.
Read more >
React: Form Validation (having nested schema) with Formik ...
Here, because of the nested object, we're setting error and helperText values differently. We're using a helper function getIn() provided by ...
Read more >
React: Form Validation (Nested schema) with ... - Tealfeed
This article shows how to validate forms and show error messages with Formik, Yup, and Material-UI. Most importantly it shows nested object properties ......
Read more >
JSON Schema validation (nested objects, arrays) in Postman
In this tutorial, we will look at more advanced things regarding JSON schema validation : for example ( nested objects, arrays…).
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found