Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda