In this lesson we'll show how to setup a nested validation structure using the yup
library. We'll then use the yup.lazy
method to evaluate the value
at runtime and adjust our validation schema. We'll make our nested validation optional only if our optionalObject
actually exists.
Instructor: [00:00] The Yup validation library allows for dynamic validation rules based upon the data. We'll first start by setting up a rule that will validate some nested data. We're going to say a Yup.object.shape. Now, we can define a shape schema.
[00:17] We'll give an optional object, and say this is a Yup.object.shape as well. Then we'll just have some other data that is a Yup.string that's required. With this, if we toggle to our browser, we can see that our data is no longer valid.
[00:42] However, if we removed the code that we added, went back to our browser, everything's true. However, we want this particular object and its nested data to only validate if it exists. We can do that using the Yup.lazy function.
[01:01] We can say Yup.lazy, which will receive a function. We're going to copy this. That function will be called with the value. Now, we can determine based upon the value whether or not we need to dynamically change the validation rules.
[01:22] In our case, if the value is defined, and that value's going to be this optional object, if it is an object essentially, or if it's basically not undefined, then we will return our validation rule. We'll say if value doesn't equal undefined, then we'll return what we had there previously.
[01:45] However, because we always need to return some sort of validation schema, we're going to return a not required mix. We're going to say return Yup.mixed, which mixed is what all of the base validation extends from, so string, etc. Then we'll return not required.
[02:08] Now, if we look at our browser, we can see that we're valid. That's because we're trying to validate our state, which is empty. Now, if we were to add some sort of button press that will add the optional data, so we'll say onClick.
[02:24] We'll do a this.setState. Inside of there, we're going to add our optional object. We're just going to pass in an object. When we click on this, that optional object will go from undefined to an object that we will then have this retriggered.
[02:43] We'll see when we press on this that it changes to false. That's because this then runs again. Right here, rerender happens. We validate it. It sees that the value's no longer undefined. We now have our dynamic rules that expects this shape, with other data in a string to be required.
[03:07] Just to validate that that is working, if we passed in other data with a string of test, and we press add optional, it stays true, because the data is still valid that we're attempting to validate that we set here.