I am using react-hook-form and Joi for the validataion in react. But in case of edit, if I don't touch any field and hit directly update, it shows value required, even when the field is already populated there.
But, once I focus or clicked on the input field, and hit update, then its get updated.
Here is the form:
const MarketplaceForm = ({ submitAction, submitBtnText, item }) => {
//joi schema
const schema = Joi.object({
name: Joi.string().required().min(3).max(191).label("Marketplace Name"),
});
//react hook form setup
const {
register,
handleSubmit,
setError,
clearErrors,
formState: { errors },
} = useForm({
resolver: joiResolver(schema),
});
const onSubmit = async (input) => {
submitAction(input, setError);
};
return (
<div className="intro-y box p-5">
<form id="add_marketplace_form" onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="crud-form-1" className="form-label">
Marketplace Name
</label>
<input
className={`form-control w-full ${
errors["name"] ? "border-red-500" : ""
}`}
type="text"
id="name"
name="name"
autoComplete="on"
{...register("name")}
defaultValue={item.name ?? ""}
/>
<ErrorSpan errors={errors} fieldName="name" />
</div>
<div className="text-right mt-5">
<button
type="button"
className="btn btn-outline-secondary w-24 mr-1"
>
Cancel
</button>
<button type="submit" className="btn btn-success w-24">
{submitBtnText}
</button>
</div>
</form>
</div>
);
};
export default MarketplaceForm;