react-hook-form / resolvers

📋 Validation resolvers: Yup, Zod, Superstruct, Joi, Vest, Class Validator, io-ts, Nope, computed-types, typanion, Ajv, TypeBox, ArkType, Valibot, effect-ts and VineJS
https://react-hook-form.com/
MIT License
1.69k stars 157 forks source link

Feature Request: Expose the validation schema on the formController #505

Open juliushuck opened 1 year ago

juliushuck commented 1 year ago

In my date picker component I want to access the validation schema of the form to extract the min and max values for the date directly from the validation schema to have a single source of truth. For that it would be nice to have sth like this:

const formController = useFormController({
    resolver: joiResolver(
        eventValidationSchemas.creation.forms.settings.real,
        validationOptions
    ),
    defaultValues: defaultFormData,
});

console.log(formController.validationSchema); --> Outputs the validation schema of the resolver

My way to extract the specific validation rule for joi would be

const formController = useFormControllerContext();
const fieldController = useFieldController({
    control: formController.control,
    name,
});

const getFormValidationRule = (formController, field, ruleName) => {
    let schema = formController?.validationSchema;
    field.split(".").forEach((x) => {
        schema = schema?._ids?._byKey?.get(x)?.schema;
    });
    return schema?._rules?.find((rule) => rule.name === ruleName);
};

const minDate = day(getFormValidationRule(formController, name, "min")?.args?.date);
const maxDate = day(getFormValidationRule(formController, name, "max")?.args?.date);

For that to work, the joiResolver function would have to return an object or so to the form controller, which can then expose the schma and use the resolver function to validate the data.

I could also wrap the formController for my purpose, but I think it would be nice to include this functionality by default.

bluebill1049 commented 1 year ago

I would like to have this feature, however, finding consistency cross all different lib is challenging, would be good for each lib has a way to serialize the schema to a JSON format so hook form can easily consume, but the only visible option right now is probably what you suggested and JSON schema.

const formController = useFormController({
    resolver: joiResolver(
        eventValidationSchemas.creation.forms.settings.real, // why not just export this?
        validationOptions
    ),
    defaultValues: defaultFormData,
});