React input 특수문자 제한 - react input teugsumunja jehan

보통 검증할 때 material + formik 조합으로 많이 사용하는데, 기존 formik은 무언가 버튼을 눌러서 submit 요청을 보내야 그 밑에 helperText가 뜨는 구조였다. 

 

하지만, 내가 원하는 건 onChange 시에 바로바로 검증을 하여 helperText가 뜨는 구조를 원했다.

 

그래서 아래처럼 노가다를 진행했다.💤

 

Input Component

props
  • type : input의 type
  • label : input의 제목
  • value : input의 value
  • maxValue : input이 가질 수 있는 최대 글자수
  • setValue : value가 바뀌면 부모컴포넌트에있는 state에 저장시키기 위한 함수
  • regexCheck 또는 check함수 둘 중에 하나만 있으면 됩니다.
  • regexCheck : validation 할 정규표현식
  • successText : test 통과했을 때 나타나는 문구
  • errorText : test 실패했을 때 나타나는 문구
  • defaultText : 기본값 또는 빈값일때 나타나는 문구
state
  • isError : true면 material의 TextField의 error 기능을 작동시키는 역할. (이를 통해, 인풋의 색깔이 빨갛게 바뀐다.)
  • helperText : helperText를 저장하고, 변경시키는 역할
import React, { useState } from "react";
import styled from "@emotion/styled";
import { TextField } from "@mui/material";

export default function ValidationInput({
  label,
  type,
  value,
  maxValue,
  setValue,
  regexCheck,
  successText,
  errorText,
  defaultText
}) {
  const [isError, setIsError] = useState(true);
  const [helperText, setHelperText] = useState(defaultText);

  const HandleOnChange = (e) => {
    //최대값이 지정되어있으면 value를 저장하지 않는다.
    if (maxValue && maxValue < e.target.value.length) return;

    setValue(e.target.value);

    //공백인 경우 defaultText로 바꾼다.
    if (e.target.value === "") {
      setIsError(true);
      return setHelperText(defaultText);
    }

    if (regexCheck) {
      // 정규표현식체크가 통과되면 successText를 송출하고 아니면 errorText를 송출한다
      if (regexCheck.test(e.target.value)) {
        setIsError(false);
        return setHelperText(successText);
      }
      if (!regexCheck.test(e.target.value)) {
        setIsError(true);
        setHelperText(errorText);
      }
    }
  };

  return (
    <div>
      <Label>{label}</Label>
      <TextField
        error={isError}
        id="standard-error-helper-text"
        helperText={helperText}
        variant="standard"
        type={type}
        onChange={HandleOnChange}
        value={value}
      />
    </div>
  );
}

ValidationInput.defaultProps = {
  type: "text",
  label: "",
  value: ""
};

const Label = styled.span`
  color: #878787;
  font-size: 18px;
`;

 

Regex

정규식을 통하여 검사를 하게끔 하였다.

//한국어+글자수(3글자 이상,10글자 이하)
const nickname = /^[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]{3,10}$/;

//email형식
const email = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;

//영어소문자+숫자+특수문자(_,-)+글자수(6글자 이상, 10글자 이하)
const password = /^[a-z0-9_-]{6,10}$/;

const regex = { nickname, email, password };

export default regex;

 

Parent Component

Input Components에 필요한 정보를 하나하나씩 보내주었다.

import React, { useState } from "react";
import ValidateInput from "../src/Components/Shared/ValidateInput";

import regex from "../src/Shared/regex";


const App = () => {
  const [nickInput, setNickInput] = useState("");
  const [emailInput, setEmailInput] = useState("");
  const [passwordInput, setPasswordInput] = useState("");

  return (
    <>
      <ValidationInput
        label="닉네임"
        value={nickInput}
        setValue={setNickInput}
        maxValue={10}
        regexCheck={regex.nickname}
        defaultText="닉네임을 입력해주세요!"
        successText="통과"
        errorText="한글사랑 나라사랑, 3글자 이상!"
      />
      <ValidationInput
        label="이메일"
        value={emailInput}
        setValue={setEmailInput}
        regexCheck={regex.email}
        defaultText="이메일을 입력해주세요!"
        successText="통과"
        errorText="이메일 양식!"
      />
      <ValidationInput
        label="패스워드"
        type="password"
        value={passwordInput}
        setValue={setPasswordInput}
        regexCheck={regex.password}
        maxValue={10}
        defaultText="이메일을 입력해주세요!"
        successText="통과"
        errorText="소문자, 6글자 이상!"
      />
    </>
  );
};

export default App;

 

완성

React input 특수문자 제한 - react input teugsumunja jehan

 

한 번 더 Develop! 🙄

중복확인 버튼을 만들어서 서버랑 통신하는 api를 연결할 수 있게 더 develop을 했다. disabled 속성을 통하여, 중복체크에 통과되지 않으면 버튼이 눌려지지 않도록 했다.  크으.. 내가 생각해도 너무 잘했다.. 다음에 다른 프로젝트에서 다시 써먹어야지

특수문자를 정규식을 사용해서 막기

onkeyup  과  ononkeydown  에서 현재 입력창의 값을 받아서 처리 한다.

function check(obj){
        //정규식으로 특수문자 판별
        var regExp = /[ \{\}\[\]\/?.,;:|\)*~`!^\-_+┼<>@\#$%&\'\"\\\(\=]/gi;
        
        //배열에서 하나씩 값을 비교
        if( regExp.test(obj.value) ){
           //값이 일치하면 문자를 삭제
           obj.value = obj.value.substring( 0 , obj.value.length - 1 ); 
        }
      }

input text를 사용하다보면 숫자만 입력 받는다거나, 특수문자는 입력하지 못하게 하는 등의 입력 

제한이 필요한 때가 많이 있습니다.


Javascript의 match와 정규식을 활용하면 간단하게 입력 제한을 걸어줄 수 있습니다.



case 1. 특수문자 입력을 제한





다음과 같이 특수문자 < > ( ) 의 입력을 제한해야 하는 input이 있습니다.



1
<input type="text" id="inputId" maxlength="30" />



Javascript로 입력 제한할 특수문자의 정규식과 match, keyup, focusout 메소드를 사용하여 
간단하게 해결할 수 있습니다.



<script>
    
    // 입력을 제한 할 특수문자의 정규식
    var replaceId  = /[<>()]/gi;
    
    $(document).ready(function(){
        
        $("#inputId").on("focusout", function() {
            var x = $(this).val();
            if (x.length > 0) {
                if (x.match(replaceId)) {
                   x = x.replace(replaceId, "");
                }
                $(this).val(x);
            }
        }).on("keyup", function() {
            $(this).val($(this).val().replace(replaceId, ""));

        });

    });
 
</script>








case 2. 숫자만 입력하도록 제한


마찬가지로 숫자만 입력받아야 하는 input이 있습니다.


<input type="text" id="inputPhone" maxlength="30" />


역시 Javascript로 간단하게 해결할 수 있습니다.


<script>
    
    // 숫자가 아닌 정규식
    var replaceNotInt = /[^0-9]/gi;
    
    $(document).ready(function(){
        
        $("#inputPhone").on("focusout", function() {
            var x = $(this).val();
            if (x.length > 0) {
                if (x.match(replaceNotInt)) {
                   x = x.replace(replaceNotInt, "");
                }
                $(this).val(x);
            }
        }).on("keyup", function() {
            $(this).val($(this).val().replace(replaceNotInt, ""));
        });
 
    });
 
</script>









case 3. 숫자, 특수문자, 불완성형 한글을 제외하여 입력하도록 제한


이번에는 숫자, 특수문자, 불완성형 한글을 제외하여 입력받아야 하는 input이 있습니다.


<input type="text" id="inputName" maxlength="30" />


한글을 완성하기 위해서는 자음 모음이 연달아 입력이 되어야 합니다. 

따라서 불완성형 한글을 검사하는 부분은 focusout에서만 실행해야 한글이 정상 입력이 됩니다. 



특수문자를 치환하는 부분은 이전처럼 keyup과 focusout에 동일하게 걸어줍니다.


<script>    
 
    // 특수문자 정규식 변수(공백 미포함)
    var replaceChar = /[~!@\#$%^&*\()\-=+_'\;<>0-9\/.\`:\"\\,\[\]?|{}]/gi;
 
    // 완성형 아닌 한글 정규식
    var replaceNotFullKorean = /[ㄱ-ㅎㅏ-ㅣ]/gi;
    
    $(document).ready(function(){
        
        $("#inputName").on("focusout", function() {
            var x = $(this).val();
            if (x.length > 0) {
                if (x.match(replaceChar) || x.match(replaceNotFullKorean)) {
                    x = x.replace(replaceChar, "").replace(replaceNotFullKorean, "");
                }
                $(this).val(x);
            }
            }).on("keyup", function() {
                $(this).val($(this).val().replace(replaceChar, ""));

       });

    });       
    
 
</script>



이를 활용하면 다양한 제한들을 간단하게 걸어줄 수 있습니다.

출처 : https://developersp.tistory.com/11

공유하기

게시글 관리

구독하기그냥저냥

저작자표시

'제이쿼리 & 자바스크립트' 카테고리의 다른 글

input 한글만 영문만 숫자만  (0)2019.10.28input checked 체크박스.  (0)2018.09.20태그 갯수 세고 각 태그별 속성주기  (0)2018.01.22placeholder 대체. input focus. input 값 클래스 넣기  (0)2017.10.27마우스 휠 중복 과다 제어 막기  (1)2017.09.05