Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Setting leading 0's in an input when number is less than 10 cant clear 0's

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!