Reputation: 63
I'm trying to set up a React form and have a number input field for the day, month, and year (Just starting in coding). I want to limit the maximum input value of the day to represent the days in the month.
I have tried using an if statement, which produces the correct result. I figured that the if statement would pull the data if called after the alteration of the month value and would kick an html5 error on submitting the form. this didn't work.
import { useState } from "react";
import { useCookies } from 'react-cookie'
import { useNavigate } from "react-router-dom";
import axios from "axios";
const handleChange = (e) => {
const value =
e.target.type === "checkbox" ? e.target.checked : e.target.value;
const name = e.target.name;
const maxDayInMonth = (month, year) =>{
if(month === 2 && year % 4 !== 0){
setMaxDay = 28
} else if(month === 2 && year % 4 === 0){
return 29
} else if(month === 4 || month === 6 || month === 9 || month === 11){
return 30
} else {
return 31
}
}
const minYear = new Date().getFullYear() - 100
const maxYear = new Date().getFullYear() - 18
return (
<>
<input
id="dob_day"
type="number"
name="dob_day"
placeholder="DD"
min = "1"
max = {maxDayInMonth(formData.dob_month, formData.dob_year)}
required={true}
value={formData.dob_day}
onChange={handleChange}
/>
<input
id="dob_month"
type="number"
name="dob_month"
placeholder="MM"
min = "1"
max = "12"
required={true}
value={formData.dob_month}
onChange={handleChange}
/>
<input
id="dob_year"
type="number"
name="dob_year"
placeholder="YYYY"
min = {minYear}
max = {maxYear}
required={true}
value={formData.dob_year}
onChange={handleChange}
/>
</>
)
What am I not doing in order to make it work?
I just thought that maybe I should use a useState as there is a modification resulting from user input, but since I typed this out I'm going to ask, in case I am wrong.
Upvotes: 0
Views: 443
Reputation: 16199
const[selectedDay,setSelectedDay] = useState(1)
const[selectedMonth,setSelectedMonth] = useState(1)
const[selectedYear,setSelectedYear] = useState(2000)
then you replace your handleChange with this function :
const getValue = (e) => {
return e.target.type === "checkbox" ? e.target.checked : e.target.value;
}
in your inputs :
//Year
<input
value={selectedYear}
onChange={(e) => {
setSelectedYear(getValue(e))
}}
/>
// Month
<input
value={selectedMonth}
onChange={(e) => {
setSelectedMonth(getValue(e))
}}
/>
<input
max = {maxDayInMonth(selectedMonth,selectedYear)}
value={selectedDay}
onChange={(e) => {
setSelectedDay(getValue (e))
}
/>
Upvotes: 1