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.66k stars 150 forks source link

Why Hookform resolver makes required fields optional? #683

Open ritikbanger opened 1 month ago

ritikbanger commented 1 month ago

Describe the bug Hookform Resolver is making types optional.

To Reproduce Steps to reproduce the behavior:

export const loginValidationSchema = () =>
    yup.object().shape({
        email: yup
            .string()
            .trim()
            .required("email_req")
            .email("email_invalid")
            .matches(EMAIL_REGEX, "email_invalid"),
        password: yup.string().required("pass_req"),
        rememberMe: yup.boolean().required(),
    });

export interface ILogin {
    email: string;
    password: string;
    rememberMe: boolean;
}

    const {
        control,
        handleSubmit,
        setValue,
        formState: { errors },
    } = useForm({
        mode: "onChange",
        resolver: yupResolver<ILogin>(loginValidationSchema()),
    });

In the onSubmit of form I get:

handleSubmit((data) => {onSubmit(data);})

The type that gets resolved is:

data: {
    rememberMe?: boolean;
    email?: string;
    password?: string;
}

This is because the type that get resolved here is:

resolver?: Resolver<{
    rememberMe?: boolean;
    email?: string;
    password?: string;
}, any>

Codesandbox link (Required) Include a codesandbox will help us to investigate the issue quicker.

Expected behavior The type should be inferred as required and not optional which is

 interface ILogin {
    email: string;
    password: string;
    rememberMe: boolean;
}

Screenshots image

image

image

Desktop (please complete the following information):

ritikbanger commented 6 days ago

Any update on this?

jorisre commented 5 days ago

Can you please provide an updated Codesandbox with your issue?

ritikbanger commented 4 days ago

simply hover on the methods like resolver to know what is wrong. I have screenshots attached of what method to hover on.

jorisre commented 4 days ago

I need a reproducible example to help you. Can you provide a Codesandbox or more details?

ritikbanger commented 4 days ago

https://codesandbox.io/s/react-hook-form-validationschema-v6-2l77g

jorisre commented 4 days ago

Your CSB is not using the same version of RHF and resolvers as described in your issue. Please ensure consistency.

ritikbanger commented 3 days ago

This problem occur only when we don't use register and use controlled components by using control. I will share a CSB with control implementation.