简体   繁体   中英

How to set max date allowed to the user to select in React.js

How to allow the user to select a date in the future (maximum the current date + 3 months)?

I have tried below code but it is allowing all future dates. Dates are not disabled after 3 months from current date. I don't want to use a date picker or any date NPM packages.

const [eventDate, setEventDate] = useState(moment())
const eventFutureDate = useState(moment().add(3,'m'))

<Form.Control
  type="date"
  placeholder="select date" name="date"
  value={moment(eventDate).format("YYYY-MM-DD")}
  max={moment(eventFutureDate).format("YYYY-MM-DD")}
  onChange={(e) => setEventDate(e.target.value)}
/>

If you're using moment.js, which is not recommended , you need to use a capital M inside the add method: moment().add(3,'M') .

You should consider replacing moment.js with date-fns though; it's a lot smaller and faster.

Another improvement would be to store the formatted date in the state as event.target.value in your onChange is already formatted. And you don't need to use state for your eventFutureDate if you don't change it.

Check the code below:

import addMonths from 'date-fns/addMonths';
import format from 'date-fns/format';

...

const [eventDate, setEventDate] = useState(format(new Date(), "yyyy-MM-dd"));
const maxDate = format(addMonths(new Date(), 3), "yyyy-MM-dd");

...

<Form.Control
  type="date"
  max={maxDate}
  name="date"
  onChange={(e) => setEventDate(e.target.value)}
  placeholder="select date"
  value={eventDate}
/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM