aotoyae

[JS] input maxlength : 한글, 숫자 입력 시 오류 해결 & e.target 구조분해 본문

JavaScript

[JS] input maxlength : 한글, 숫자 입력 시 오류 해결 & e.target 구조분해

aotoyae 2024. 2. 17. 04:40

 

 

💡 input 에 한글이나 숫자를 입력할 때 maxlength 가 부자연스러운 동작을 하는데,
원하는 글자수로 딱 제한할 수 있도록 해결해보자!

 

 

<input
  type="text"
  value={nickName}
  onChange={(e) => setNickName(e.target.value)}
  placeholder="최대 20자"
  maxLength={20}
/>

 

maxLength 로 제한을 두니 한글을 입력했을 때나,

숫자 + 한글을 입력했을 때 21 자가 입력이 되버린다.

 

⬇️

const handleOnInput = (e, maxlength) => {
  const { target: { value }, } = e;
  if (value.length > maxlength) e.target.value = value.substr(0, maxlength);
};
  
// ...

<input
  type="text"
  value={nickName}
  onInput={(e) => handleOnInput(e, 20)}
  onChange={(e) => setNickName(e.target.value)}
  placeholder="최대 20자"
/>

 

이렇게 input 값의 길이가 설정한 maxlength 보다 길면

0 ~ maxlength 까지 잘라주는 함수로 오류를 해결할 수 있다!

 

 

숫자와 한글을 조합했을 때 원했던 20자까지 잘 입력된다.

 

 

 

🔗 https://hianna.tistory.com/435

 

[Javascript] input 에서 입력 글자수 제한하는 2가지 방법

Javascript의 input 폼에 입력되는 최대 글자수를 제한하는 방법 2가지를 알아보도록 하겠습니다. 1. maxlength 속성 사용하기 2. 입력된 글자수를 체크로직 구현하기 1. maxlength 속성 사용하기 maxlength 속

hianna.tistory.com

🔗 https://velog.io/@seoyul0203/REACT%EA%B5%AC%EC%A1%B0%EB%B6%84%ED%95%B4-%ED%95%A0%EB%8B%B9-%EC%98%88%EC%8B%9C

 

[REACT]구조분해 할당 예시

객체의 구조분해

velog.io

🔗 https://whales.tistory.com/97

 

ES6 : 구조할당(feat.이벤트 값 핸들링)

ES6 내용 중 이전에 정리를 했었지만 스스로 제대로 이해를 하지 못하고 있는 거 같아서 다시 한번 내용을 정리해 보려 합니다. 구조 분해 할당이란 배열이나 객체의 값을 원하는 개별 변수에 할

whales.tistory.com