zod generic validation using object property and user inputs

27 Views Asked by At

I created a generic filter by muti selection fields and the value to filter is in input field

  1. select the property.
  2. choode operator to filter
  3. input the vlaues to filter

I need to validate using the relation between the object property and the values

export const FilterItem = <T extends SomeZodObject>(dataType: T) =>
    z
        .object({
            Field: z.string().refine(
                d => {
                    return Object.keys(dataType.keyof().Enum).some(
                        k => k.toLocaleLowerCase() === d.toLocaleLowerCase(),
                    );
                },
                {
                    path: [],
                },
            ),
            Operator: filterOperatorSchema,
            Value: z.any(),
        })
        .refine(
            data => {
                const _type = Object.entries(dataType.shape).find(
                    ([key]) => key.toLocaleLowerCase() === data.Field.toLocaleLowerCase(),
                );

                if (
                    !_type ||
                    Object.keys(_type).length === 0 ||
                    !_type[1]?._def.typeName
                )
                    return false;

                if (isArray(data.Value)) {
                    return Array.from(data.Value).every(
                        v => _type[1].safeParse(v).success,
                    );
                } else {

                    return _type[1].safeParse(data.Value).success;
                }
            },
            {
                message: "Field and Value types not the same",
                path: ["Value"],
            },
        );

value is an input field so, data type is string. how to coerce the input and use it in the custom validation : like numbers is treated as string

0

There are 0 best solutions below