To accomplish the previously mentioned goal, I would adopt this method:
import React, { useState } from 'react';
const DateTimeValidator = () => {
const [date, setDate] = useState('');
const [time, setTime] = useState('');
const [validationMessage, setValidationMessage] = useState('');
const handleDateChange = (e) => {
setDate(e.target.value);
validateDateTime(e.target.value, time);
};
const handleTimeChange = (e) => {
setTime(e.target.value);
validateDateTime(date, e.target.value);
};
const validateDateTime = (selectedDate, selectedTime) => {
const currentDate = new Date();
const selectedDateTime = new Date(`${selectedDate}T${selectedTime}`);
if (selectedDate && selectedTime && selectedDateTime > currentDate) {
setValidationMessage('Please select a past time.');
} else {
setValidationMessage('');
}
};
return (
<div>
<input type="date" onChange={handleDateChange} />
<input type="time" onChange={handleTimeChange} />
{validationMessage && <small>{validationMessage}</small>}
</div>
);
};
export default DateTimeValidator;
Let's walk through the code provided above:
handleDateChange
updates the date state and handleTimeChange
updates the time state. Both functions then call validateDateTime
to evaluate the selected date and time. The validateDateTime
function constructs a Date object based on the chosen date and time inputs, compares them to the current date and time, and verifies whether they are in the future.