When working with forms that require users to select a date, you often need to prevent them from choosing past dates—especially for scenarios like booking appointments or making reservations. This is a common requirement in many applications, and luckily, HTML and JavaScript provide a simple way to handle this.
The HTML Date Input
The <input>
element with type="date"
allows users to pick a date easily. However, by default, the user can select any date, including past ones. To restrict users from selecting a date before the current day, you can use the min
attribute in conjunction with JavaScript.
Example HTML Date Input
Here’s an example of a simple date input:
<input type="date" id="reservationDate" name="reservationDate" />
Disabling Past Dates
To prevent users from selecting a past date, you need to set the min
attribute of the <input type="date">
field. The min
attribute specifies the minimum date that can be selected.
You can dynamically set the current date using JavaScript’s Date
object, format it to the required YYYY-MM-DD
format, and apply it to the min
attribute.
Implementation in React
For React users, here’s how you can integrate this into a TextField
component:
import { TextField } from "@mui/material";
import { Field } from "formik";
const ReservationDateField = ({ touched, errors }) => {
return (
<Field
as={TextField}
label="Reservation Date"
type="date"
name="reservationDate"
fullWidth
margin="normal"
InputLabelProps={{ shrink: true }}
InputProps={{
inputProps: {
min: new Date().toISOString().split("T")[0], // Disable past dates
},
}}
error={touched.reservationDate && Boolean(errors.reservationDate)}
helperText={touched.reservationDate && errors.reservationDate}
/>
);
};
Breakdown:
-
Date Formatting:
new Date().toISOString().split("T")[0]
gives today’s date inYYYY-MM-DD
format, which is required for themin
attribute. - min Attribute: This ensures users can only select dates from today onwards.
Why is This Important?
Restricting past dates is essential in forms that manage future events like:
- Booking appointments.
- Scheduling deliveries.
- Setting future reminders.
It improves user experience by preventing invalid date selections and reduces the likelihood of user error.
Conclusion
Disabling past dates is a simple yet powerful way to improve your forms. Whether you’re a beginner or an experienced developer, applying this technique ensures your users don’t accidentally select incorrect dates. This small step can make a big difference in your application's usability.
Top comments (1)
Thanks for the article. I think you don’t have to remove timezone from date string.