Home > Enterprise >  I want to validate minDate and maxDate in reactjs as maxDate should be minDate 5yrs
I want to validate minDate and maxDate in reactjs as maxDate should be minDate 5yrs

Time:11-22

minDate = today

maxDate = minDate 5yrs

I did not try anything. Asking for solution

CodePudding user response:

You can have a variable which will contains the date of today, and set it as a minDate and then add to it 5 years and use it as a maxDate

const currentDate = new Date()

function addYears(date, years) {
  date.setFullYear(date.getFullYear()   years);
  return date;
}

  return (
    <DatePicker
      ...props here
      minDate={currentDate}
      maxDate={addYears(currentDate, 5)}
    />
  );

CodePudding user response:

If you already have dayjs, you can do something like

const minDate = dayjs();
const maxDate = minDate.add(5, 'year');
// const maxDate = minDate.add(5, 'y');

return (
  <DatePicker
    ...props
    minDate={minDate}
    maxDate={maxDate}
  />
);

CodePudding user response:

import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";


() => {
  const [startDate, setStartDate] = useState(null);
  return (
    <DatePicker
      selected={startDate}
      onChange={(date) => setStartDate(date)}
      minDate={new Date()}
      maxDate={addMonths(new Date(), 60)}
      placeholderText="Select a date between today and 5 years in the future"
    />
  );
};
  • Related