The situation Im dealing with is: When a user inputs a single digit number less than 10 in a month or day field I want to add a 0 in front so the date can be displayed MM or DD. I have read so many solutions to this issue and tried to implement them as suggested but everything Ive tried so far is very buggy.
The bug Im dealing with right now is, although my Input field is set to a maxLength
of 2
when I try and type in a new date the 0 never falls off so i end up with a 3 digit value in the field.
My date input Ill leave out the last 2 they have all the same attributes...Please NOTE there are 3 separate inputs for the date not just one:
<div className="nh-date">
<Input
onChange={onDateInputChange("month")}
value={date.month}
className={`nh-mon ${error.includes("month") ? "error" : ""}`}
name="month"
id="mon"
placeholder="00"
maxLength={2}
type="number"
selectTextOnFocus={true}
/>
<span className="sep">/</span>
...
My onChange function:
const onDateInputChange = (field: string) => (e: any) => {
let d = e.target.value;
if ((field === "month" || field === "day") && d.length === 1) {
d = "0" + d;
setInputDate({ ...inputDate, [field]: d });
setError([]);
}
if ((field === "month" && d > 12) || (field === "day" && d > 31)) {
setError([field]);
}
if (field === "year" && d.length === 0) {
setError([field]);
} else if (d.length > 2) {
// d = d.replace(/^0+/, "");
setInputDate({ ...inputDate, [field]: d });
setError([]);
}
I think my main issue is that I can never clear the 0's
out of the field. Once I add a value to the field it's unchangeable. My whole goal is to just validate 3 input fields to get a date formatted like MM/DD/YY
. Any advice would be super helpful.