js 한글/영문만 입력 허용

기여·2024년 6월 16일
0

소소한 개발팁

목록 보기
37/103

좋은 점: 뭔가 정교하고 깔끔하고 규칙적이고 있어 보임;
아쉬운 점: 테스트할 때 약간 킹받음 😤

예제:

<script>
//한글이름 scr
function validateKorean(input) {
    const koreanRegex = /^[ㄱ-ㅎㅏ-ㅣ가-힣\s]*$/;
    if (!koreanRegex.test(input.value)) {
        alert("한글만 입력 가능합니다.");
        input.value = input.value.replace(/[^\ㄱ-ㅎㅏ-ㅣ가-힣\s]/g, '');
    }
}
//한글이름 scr 끝

//영문이름 scr
function validateEnglish(input) {
    const englishRegex = /^[A-Za-z\s]*$/;
    if (!englishRegex.test(input.value)) {
        alert("영문만 입력 가능합니다.");
        input.value = input.value.replace(/[^A-Za-z\s]/g, '');
    }
}
//영문이름 scr 끝
</script>
			<tr>
            <th><p>한글 이름:</p></<th>
            <td><input class="input" type="text" name="custName" 
            placeholder="홍길동" oninput="validateKorean(this)" required></td>
            </tr>
            
            <tr>
            <th><p>영문 이름:</p></th>
            <td><input class="input" type="text" name="engName" 
            placeholder="HONG GIL DONG" oninput="validateEnglish(this)" required>
            </td>
            </tr>

결과:

영문 경우의 캡처는 생략~

profile
기기 좋아하는 여자

0개의 댓글