Skip to content
input실무 경험

Using a Regex to Allow Only Numbers in input type = "text"

1 min readWorkMoved from my Tistory blogRead the Korean original

Today at work, while validating an input that takes a car's paint film thickness, I had the following conditions.

  • The number of digits (length) is 5 or fewer

  • No e (exponent), letters, or .

Validating an input of type number against these conditions seemed tricky, so I set the input type to text.

I used maxLength for the maximum string length and a regular expression for the other conditions.

At work I implemented it with jsp + vue.js, but I can't share company code, so I reviewed it on my own at home using React.

tsx
import React, { useState } from "react";

const YourComponent = () => {
  const [inputValue, setInputValue] = useState("");

  const handleInputValue = (e: React.ChangeEvent<HTMLInputElement>) => {
    // const validInputValue = e.target.value.toString().split('').map((str)=>{
    //   if(!isNaN(str) && str !== '.' && str !=='e'){
    //       return str
    //   }
    // }).join('')

    const validInputValue = e.target.value.replace(/[^0-9]/g, "");
    setInputValue(validInputValue);
  };

  return (
    <>
      <input
        type="text"
        maxLength={5}
        name="test"
        id="test"
        value={inputValue}
        onChange={(e) => handleInputValue(e)}
      />
      <button type="submit">제출</button>
    </>
  );
};

export default YourComponent;

The regex that allows only numbers is below. When I implemented this before, I went through the characters one by one with the split() method and validated them myself, but using the replace() function with a regex made it simple to implement.

js
const validInputValue = e.target.value.replace(/[^0-9]/g, "");

Below is the implemented screen.

  • #Regex to Block Periods
  • #input text Length Limit
  • #Number Input in input type text
  • #React
  • #Vue.js
  • #Regular Expression
  • #Exponent (e)

More in Work