resolvers icon indicating copy to clipboard operation
resolvers copied to clipboard

Why Hookform resolver makes required fields optional?

Open ritikbanger opened this issue 1 year ago • 7 comments

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):

  • OS: [e.g. iOS] Ubuntu
  • Browser [e.g. chrome, safari] Chrome
  • Version [e.g. 22] Version "@hookform/resolvers": "^3.4.0", "yup": "^1.4.0", "react-hook-form": "^7.51.4",

ritikbanger avatar May 16 '24 11:05 ritikbanger

Any update on this?

ritikbanger avatar Jul 01 '24 07:07 ritikbanger

Can you please provide an updated Codesandbox with your issue?

jorisre avatar Jul 02 '24 19:07 jorisre

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

ritikbanger avatar Jul 03 '24 07:07 ritikbanger

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

jorisre avatar Jul 03 '24 07:07 jorisre

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

ritikbanger avatar Jul 03 '24 08:07 ritikbanger

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

jorisre avatar Jul 03 '24 08:07 jorisre

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.

ritikbanger avatar Jul 04 '24 14:07 ritikbanger