boba poorna
boba poorna

Reputation: 251

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)}
/>

Upvotes: 1

Views: 1170

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23160

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}
/> 

Upvotes: 1

Related Questions