Since a person can't die before he/she is born it makes sense to have a min and max for these dates. But I can't get the value from the 1st input, I get an error that the value is null. (Using the react-hooks-form package, don't think this information is important but you never know)
<div className="form-section">
<label>Date of birth <span style={{ color: "red " }}>*</span>:</label>
{errors.Name && errors.Name.type === "required" && (
<span style={{ color: "red " }}>Required!</span>
)}
<input
max={moment().format("YYYY-MM-DD")}
type="date"
name="BirthDate"
id="BD"
ref={register({ required: true })}
/>
</div>
<div className="form-section">
<label>Date of death <span style={{ color: "red " }}>*</span>:</label>
{errors.Name && errors.Name.type === "required" && (
<span style={{ color: "red " }}>Required!</span>
)}
<input
min={document.getElementById("BD").value}
max={moment().format("YYYY-MM-DD")}
type="date"
name="DateOfDeath"
ref={register({ required: true })}
/>
</div>
Thanks for the help! I can add extra information if needed.
CodePudding user response:
As the code in questions contains incomplete structure I'm formatting here as per my understanding. If you can provide a working example on codesandbox then it will be a great help.
You need to use watch from react-hook-form.
const MyComponent = () => {
const {
register,
errors,
watch,
} = useForm();
const dateOfBirth = watch('BirthDate', new Date()); // Added new date to default to Today in case if DOB is not selected.
return (
<div className="form-section">
<label>Date of birth <span style={{ color: "red " }}>*</span>:</label>
{errors.Name && errors.Name.type === "required" && (
<span style={{ color: "red " }}>Required!</span>
)}
<input
max={moment().format("YYYY-MM-DD")}
type="date"
name="BirthDate"
id="BD"
ref={register({ required: true })}
/>
</div>
<div className="form-section">
<label>Date of death <span style={{ color: "red " }}>*</span>:</label>
{errors.Name && errors.Name.type === "required" && (
<span style={{ color: "red " }}>Required!</span>
)}
<input
min={dateOfBirth}
max={moment().format("YYYY-MM-DD")}
type="date"
name="DateOfDeath"
ref={register({ required: true })}
/>
</div>)
}