I have a field for adding date of birth in my project’s registration page. A registering user should be at least 18 years old. The problem is that even though the validation works, it is not outputting any error message on the screen around the field.
`
const validateForm = async (currentFormData = formData) => {
const errors = {};
if (!currentFormData.name) errors.name = "This field cannot be empty";
if (!currentFormData.surname) errors.surname = "This field cannot be empty";
if (!currentFormData.email) {
errors.email = "This field cannot be empty";
} else if (!validateEmail(currentFormData.email)) {
errors.email = "Please enter a valid email address";
}
if (!currentFormData.dateOfBirth) {
errors.dateOfBirth = "Please enter a complete date of birth";
} else if (!isAtLeast18YearsOld(currentFormData.dateOfBirth)) {
errors.dateOfBirth = "You must be at least 18 years old to register";
}
if (!currentFormData.password) {
errors.password = "This field cannot be empty";
} else if (!validatePassword(currentFormData.password)) {
errors.password = "Password does not meet requirements";
}
if (currentFormData.password !== currentFormData.confirmPassword) errors.confirmPassword = "Passwords do not match";
if (role === 'city') {
if (!currentFormData.cityName) {
errors.cityName = "This field cannot be empty";
} else {
currentFormData.cityName = capitalizeName(currentFormData.cityName);
}
if (!currentFormData.cityID) {
errors.cityID = "This field cannot be empty";
} else {
const isValid = await isValidCityID(currentFormData.cityID);
if (!isValid) {
errors.cityID = "Invalid or already assigned City ID";
}
}
if (!currentFormData.countryName || currentFormData.countryName === "") {
errors.countryName = "Please select a country";
}
}
setFormErrors(errors);
return Object.keys(errors).length === 0;
};
const handleDateChange = (newValue) => {
setFormData(prevFormData => {
const updatedFormData = { ...prevFormData, dateOfBirth: newValue };
validateForm(updatedFormData);
return updatedFormData;
});
};
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
label="Date of Birth"
value={formData.dateOfBirth}
onChange={handleDateChange}
renderInput={(params) => (
<TextField
{...params}
error={!!formErrors.dateOfBirth}
helperText={formErrors.dateOfBirth || 'Select your date of birth'}
/>
)}
/>
</LocalizationProvider>
import { differenceInYears } from 'date-fns';
export const isAtLeast18YearsOld = (dateOfBirth) => {
const today = new Date();
const dob = new Date(dateOfBirth);
const age = differenceInYears(today, dob);
return age >= 18;
};
When I try to submit form without filling the date field or entering a wrong date, I get the logs below:
- dateOfBirth: “You must be at least 18 years old to register.”
- dateOfBirth: “Please enter your date of birth.”
New contributor
Murad Huseynov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.