Suppose i have a checkbox , it's not a required field. if user checked it a date input field will be shown. and date field is required and date must be a past date. if user unchecked the checkbox , date field will not be a required field. and no error will be shown when user submit the form . and form will be submitted . I am using react-hook-form version "^7.43.9" .
I have tried to do this like this. it's working fine but it's givinig me initially error when i give defaultValue="" and it's giving me date field is required when I checked the checkbox then did not select any date and unchecked the checkbox. Where as i want date field will be required only when checkbox is checked true, if user unchecked checkbox , date will be not required.
const validationSchema = yup.object().shape({
roofDate: yup
.date()
.typeError("Please enter a valid date")
.max(
new Date(Date.now() - 86400000),
"Date can not be future or current date"
)
.when("roofCheck", {
is: true,
then: yup.date().required("Roof date is required"),
})})
<div className="col-md-6 col-lg-3">
<div className="mb-3">
<label className="brand-label d-grid">
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="checkbox"
id="roofCheck"
name="roofCheck"
value="Roof"
{...register("roofCheck")}
/>
<label
className="form-check-label"
htmlFor="roofCheck"
>
Is Roof Updated?
</label>
</div>
</label>
{watch("roofCheck") && (
<>
<input
type="date"
id="roofDate"
className="form-control"
rules=
placeholder="Enter Roof Date"
{...register("roofDate")}
/>
</>
)}
{errors.roofDate && (
<p className="text-danger">
{errors.roofDate?.message}
</p>
)}
</div>
</div>
Aucun commentaire:
Enregistrer un commentaire