본문 바로가기
input실무 경험

input type = "text"일 때 숫자만 입력되게 정규식 이용법

1분실무 경험티스토리에서 옮긴 글

오늘 회사에서 차량의 도막을 입력받는 input의 validation을 검증하던 도중 조건이 아래와 같았습니다.

  • 자릿수(length)는 5이하

  • e(지수), 문자,. 금지

위의 조건들을 충족하기 위해서 input type number를 vailidation 하는 건 까다롭다고 생각이 들어서 input type을 text로 지정한 뒤

문자열의 최대 길이는 maxLength 효과를 이용했고 다른 조건들은 정규식을 이용했습니다.

회사에서는 jsp + vue.js를 이용해서 구현했지만 회사 코드를 공개할 수 없어서 집에서 리액트를 이용해서 혼자 복습해 보았습니다.

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;

숫자만 입력할 수 있는 정규식은 아래와 같고 이전에 구현했을 때는 split() 메서드를 통해서 문자를 하나하나 순회하면서 직접 validation 했었는데 정규식을 이용해서 replace() 함수를 이용하니 간편하게 구현할 수 있었습니다.

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

아래는 구현 화면입니다.

  • #.금지 정규식
  • #input text length 지정
  • #input text일 때 number 입력
  • #react
  • #Vue.js
  • #정규식
  • #지수(e)

실무 경험의 다른 글