0

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.

CourtneyJ
  • 458
  • 6
  • 19
  • https://stackoverflow.com/questions/1267283/how-can-i-pad-a-value-with-leading-zeros – Utkarsh Gupta Sep 21 '21 at 19:11
  • Use `d = d.toString().padStart(2,'0')`. This will convert the input to a string of minimum 2 chars with leading zero when `d` has only one char – Gil Sep 21 '21 at 19:11
  • @Gil thanks for the suggestion. However this fix created the same bug, are you suggesting I replace the `d = "0" + d;` in the first if statement with that line? Thats what i tried and it shows the same issue :/ – CourtneyJ Sep 21 '21 at 19:22
  • @CourtneyJ Then maybe something else is at play here, because this - at least, appears - to be a simple problem. Have you tried debugging it? Maybe it's something in the `setInputDate` function. – Gil Sep 21 '21 at 21:11
  • @Gil Yea Ive changed things around and Im still having the same issue. I think youre right it is an issue with `setInputDate` it doesnt update readily after the first number is entered. :/ – CourtneyJ Sep 21 '21 at 21:50
  • 1
    A more general solution would be `('00'+d).slice(-2)`, it doesn't require any prior testing and ensures the result is two characters regardless of the initial value of *d*. – RobG Sep 22 '21 at 00:57
  • For validating date values, see one of these: [*\[javascript\] how to validate a date*](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+validate+a+date) – RobG Sep 22 '21 at 01:00

0 Answers0