오늘 회사에서 차량의 도막을 입력받는 input의 validation을 검증하던 도중 조건이 아래와 같았습니다.
- 자릿수(length)는 5이하
- e(지수), 문자,. 금지
위의 조건들을 충족하기 위해서 input type number를 vailidation 하는 건 까다롭다고 생각이 들어서 input type을 text로 지정한 뒤
문자열의 최대 길이는 maxLength 효과를 이용했고 다른 조건들은 정규식을 이용했습니다.
회사에서는 jsp + vue.js를 이용해서 구현했지만 회사 코드를 공개할 수 없어서 집에서 리액트를 이용해서 혼자 복습해 보았습니다.
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() 함수를 이용하니 간편하게 구현할 수 있었습니다.
const validInputValue = e.target.value.replace(/[^0-9]/g, "");
아래는 구현 화면입니다.
'지식 정리 📝' 카테고리의 다른 글
tailWind CSS darkMode 적용 (0) | 2023.12.18 |
---|---|
jsp에서 ``(템플릿 리터럴) 정상 사용 법 (1) | 2023.12.17 |
깊은 복사(Deep copy) 경험 (0) | 2023.12.08 |
Next.js 초기 node 버전 오류 (0) | 2023.11.27 |
git merge 취소 하는 법 (0) | 2023.11.27 |