There is a form that contains two inputs, a string and a number both being required.
Here is the schema:
const schema = yup.object().shape({
name: yup.string().required(),
age: yup.number().required()
});
Afterwards, it is react-hook-form:
const { handleSubmit, reset, control, register, watch } = useForm({
defaultValues: emptyObject,
resolver: yupResolver(schema)
});
As you can see, there is defaultValues which has emptyObject.
Here it is:
const emptyObject = {
name: '',
age: 0
}
The name part works fine, I cannot submit the data if there is no input written in that textbox but for age it doesn't require any value. I know it checks for value and it finds it is 0 and it considers there is an input.
But how to change it to make it work? Tried with null but still doesn't work.
I have to mention that it is React with Typescript so there is also an interface which throws error when age is set to null.
MyData: {
name: string;
age: number;
}
CodePudding user response:
I got this from https://react-hook-form.com/get-started#Applyvalidation
import React from "react";
import { useForm, SubmitHandler } from "react-hook-form";
interface IFormInput {
firstName: string;
lastName: string;
age: number;
}
export default function App() {
const { register, handleSubmit } = useForm<IFormInput>();
const onSubmit: SubmitHandler<IFormInput> = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName", { required: true, maxLength: 20, placeHolder: "John" })} />
<input {...register("lastName", { pattern: /^[A-Za-z] $/i })} />
<input type="number" {...register("age", { min: 18, max: 99 })} />
<input type="submit" />
</form>
);
}
can this be an example to go on with?
CodePudding user response:
Make the age an empty string as well, just for your needs and when its time to submit the form just add some functionality to convert the string to number if its critical for your app.
From the DOCS, you can not set it to any undefined value:
It is encouraged that you set a defaultValue for all inputs to non-undefined such as the empty string or null.
