jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

How to validate a value in an object against the rest of the object? #2175

Closed jasekiw closed 9 months ago

jasekiw commented 9 months ago

I have a large form with many nested objects and arrays. In one of these nested objects I need to verify the field dataPointId: number matches the data points in an array at the root of the object. I have many schemas for each sub object in my form with a master schema that composes all of the sub schemas.

ex.

type DataPointDefintion = { dataPointId: number; inputs: Input[] }

type Input { ...

dataPointInput: DataPointInput | null }

type DataPointInput { dataPointId: number } type Form = { dataPointDefinitions: DataPointDefintion[] }

Here is the schema I am dealing with:

export const DataPointInputSchema = object().shape<DataPointInput>({
  dataPointId: number()
    .test('data-point-valid-reference', 'DataPointId is required', function (value: number | null)  {
      // how do I get access to the Form object here?

      return myRootObject.dataPointDefinitions.map(d => d.dataPointId).includes(value);
    }),
 ...
}, [['alertGroupId', 'dataPointId']]);

I tried .test, and .lazy but they don't seem to give me anything outside the current schema.

Being able to exclude the current path from the list of data point ids would be preferred as well to avoid a circular reference.

I am currently using yup version ^0.26.24.

jquense commented 9 months ago

lots of older issues about this. please search for them.