0

I have a simple number input in react component. I need to make it not accept more than 4 characters. But it doesn't work with maxLength attribute. What else i can do to prevent it taking more than 4 characters.

<input type="number" onchange={handleChange} 

<input type="number"/>
/>
1
  • 1
    You can find the answer here.
    – Jason Ming
    Commented Nov 30, 2023 at 7:36

2 Answers 2

1

The handleChange function checks if the input value is greater than or equal to -9999 or less than equal to 9999.

import "./styles.css";

import React, { useState } from "react";

export default App = () => {
  const [inputValue, setInputValue] = useState("");
  const handleChange = (event) => {
    const nextValue = event.target.value;

    if (nextValue >= 0 && nextValue <= 9999) {
      setInputValue(nextValue);
    }
    if (nextValue < 0 && nextValue * -1 <= 9999) {
      setInputValue(nextValue);
    }
  };

  return (
    <div>
      <label htmlFor="fourCharInput">Enter up to 4 digit number:</label>
      <input type="number" value={inputValue} onChange={handleChange} />
    </div>
  );
};

If you wanna play around with the code, here is the sandbox.

2
  • but your input is type text, i can achieve it in type text , but not in type number. It doesn't work with that. If you have any ideas for that i would be grateful. Commented Nov 30, 2023 at 8:03
  • 1
    @KonulMemmedova Thanks for pointing this out! I have made the required changes here and on the sandbox.
    – Anshu
    Commented Nov 30, 2023 at 8:28
0

you can add readonly attribute to the input when your hook gets 4 characters

Not the answer you're looking for? Browse other questions tagged or ask your own question.