Home > Software design >  most efficient way to set length restrictions on input type number in React
most efficient way to set length restrictions on input type number in React

Time:11-20

I have 3 inputs for a user to enter some values that end up being a date format

for my inputs 'day' and 'month' i want the user to enter 2 integers and no more for my input 'year' i want the user to enter 4 integers.

What is the best way to do this?

        <input
          name="month"
          value={values.dateOfBirth.month}
          onChange={(e) => handleDateChange(e)}
          type="number"
          placeholder={"MM"}
          className={dateErr ? "error" : ""}
        />
        <br />
        <input
          name="day"
          value={values.dateOfBirth.day}
          onChange={(e) => handleDateChange(e)}
          type="number"
          placeholder={"DD"}
          className={dateErr ? "error" : ""}
        />
        <br />
        <input
          name="year"
          value={values.dateOfBirth.year}
          onChange={(e) => handleDateChange(e)}
          type="number"
          placeholder={"YYYY"}
          className={dateErr ? "error" : ""}
        />

CodePudding user response:

 <input
            name="month"
            value={values.dateOfBirth.month}
            onChange={(e) => {
                if(e.target.value.length <3){
                    handleDateChange(e)
                }else {
                    e.target.value=  e.target.value.slice(0,2)
                }
            }}
            type="number"
            placeholder={"MM"}
            className={dateErr ? "error" : ""}
        />

it works for me very well.

CodePudding user response:

Try this

You can use a simple regex to allow one or two digits only. But you might add many restrictions as well.

import { useState } from "react";

export default function App() {
  const [value, setValue] = useState("");

  const handleDateChange = (e) => {
    const currentValue = e.target.value;
    if (currentValue === "") {
      setValue(currentValue);
    } else if (/^\d{1,2}$/.test(currentValue)) {
      setValue(currentValue);
    }
  };

  return (
    <div className="App">
      <input type="text" value={value} onChange={handleDateChange} />
    </div>
  );
}

Code sandbox => https://codesandbox.io/s/mystifying-browser-0ry45?file=/src/App.js

  • Related