메뉴 건너뛰기

조회 수 7142 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

키 입력을 감지해서 허용되지 않은 입력값을 바로바로 잡아주는 예제이다.

 

 

예를 들면 전화번호를 입력 받는 곳에 꼭 문자를 집어넣는 애들이 있다.

 

강제로 jquery 를 이용해서 함수를 바인드해놓고

 

포커스와 포커스 아웃을 이용해서 자동으로 문자 하나 하나 입력이 들어왔을 때 체킹하고 잘못된 입력은 삭제하는  방법이다.

 

 

 

 

1. 사용방법은 단순히 체크하고 싶은 클레스만 지정해주면 된다.

<input id="nNum" type="text" class="number">
<input id="nNum" type="text" class="onlyEnglishUpper">

 

 

 

 


 

2. js 파일을 만들어서 import한다.

 /*
     * 
     * jquery class선택자를 이용하여 자동 formatter구현
     */
    // 0) common
    function addComma(str) {
        if (str == null) {
            return "";
        }
        str = removeComma(str);
        x = str.split(".");// 소수부분리
        x1 = x[0];
        x2 = x.length > 1 ? "." + x[1] : "";
        var regex = /(\d+)(\d{3})/;
        while (regex.test(x1)) {
            x1 = x1.replace(regex, "$1" + "," + "$2");
        }
        return x1 + x2;
    }
 
    function removeComma(str) {
        str += "";
        var regex = /,/g;
        return str.replace(regex, "");
    }
 
    function formatComma(e) {
        if (keyFilter(e)) {
            $(this).val(addComma($(this).val()));
        }
    }
 
    function formatSelect() {
        $(this).select();
    }
 
    // <-(37) , ->(39)를 제외한 keyup에서만 동작
    function keyFilter(e) {
        if (e.keyCode == 37 || e.keyCode == 39)
            return false;
        else
            return true;
    }
    /**
     * flag : g = global, i = ignore case, m = multiline ^ =
     */
    // 1) money - 100,000
    function restrictMoney(e) {
        if (keyFilter(e)) {
            var regex = /[^0-9]/g;
            $(this).val($(this).val().replace(regex, ""));
        }
    }
 
    // 2) number - 100,000.00
    function restrictNumber(e) {
        if (keyFilter(e)) {
            var regex = /[^0-9\.]/g;
            $(this).val($(this).val().replace(regex, ""));
        }
    }
 
    // 3) decimal - 100000.00
    function restrictDecimal(e) {
        if (keyFilter(e)) {
            var regex = /[^0-9\.]/g;
            $(this).val($(this).val().replace(regex, ""));
        }
    }
 
    // 4) onlyNumber - 1234567890
    function restrictOnlyNumber(e) {
        if (keyFilter(e)) {
            var regex = /[^0-9]/g;
            $(this).val($(this).val().replace(regex, ""));
        }
    }
    // 5) onlyEnglish - a-z,A-Z
    function restrictOnlyEnglish(e) {
        if (keyFilter(e)) {
            var regex = /[^a-z]/gi;
            $(this).val($(this).val().replace(regex, ""));
        }
    }
    // 5-1) onlyEnglishUpper - A-Z
    function restrictOnlyEnglishUpper(e) {
        if (keyFilter(e)) {
            var regex = /[^a-z]/gi;
            $(this).val($(this).val().replace(regex, "").toUpperCase());
        }
    }
    // 5-2) onlyEnglishLower - a-z
    function restrictOnlyEnglishLower(e) {
        if (keyFilter(e)) {
            var regex = /[^a-z]/gi;
            $(this).val($(this).val().replace(regex, "").toLowerCase());
        }
    }
    // 6) forCode - 0-9,A-Z
    function restrictForCode(e) {
        if (keyFilter(e)) {
            var regex = /[^0-9a-z\_]/gi;
            $(this).val($(this).val().replace(regex, "").toUpperCase());
        }
    }
    // 7) forId - 0-9,A-Z,특수문자(_-!@#$%^)
    function restrictForId(e) {
        if (keyFilter(e)) {
            var regex = /[^0-9a-z\_\-\!\@\#\$\%\^]/gi;
            $(this).val($(this).val().replace(regex, ""));
        }
    }
 
    // 파일 확장자 체크
    function restrictFileExtension(e) {
        var ext = $(this).val().split('.').pop().toLowerCase();
 
        if ($.inArray(ext, [ 'exe', 'bat', 'sh' ]) > 0) {
            $(this).replaceWith($(this).clone(true));
            // $(this).val("");
 
            alert('허용되지 않는 확장자입니다.');
        } // end if $.inArray(ext, ['exe', 'bat', 'sh']) > 0
    }
 
    //파일 확장자 체크 Img
    function restrictFileExtensionImg(e) {
        var ext = $(this).val().split('.').pop().toLowerCase();
 
        if ($.inArray(ext, [ 'gif', 'png', 'jpg', 'jpeg' ]) == -1) { // 허용하는 확장자가 작을 경우
            $(this).replaceWith($(this).clone(true));
            // $(this).val("");
 
            alert('허용되지 않는 확장자입니다.');
        } // end if $.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1
    }
 
    // 99) class선택자로 keyup이벤트에 자동 바인딩
    $(document).ready(function() {
        // money
        $(".money").bind("keyup", restrictMoney);
        $(".money").bind("keyup", formatComma);
        $(".money").bind("focus", formatSelect);
 
        $(".money").bind("blur", restrictMoney);
        $(".money").bind("blur", formatComma);
        // number
        $(".number").bind("keyup", restrictNumber);
        $(".number").bind("keyup", formatComma);
        $(".number").bind("focus", formatSelect);
 
        $(".number").bind("blur", restrictNumber);
        $(".number").bind("blur", formatComma);
        // decimal
        $(".decimal").bind("keyup", restrictDecimal);
        $(".decimal").bind("focus", formatSelect);
 
        $(".decimal").bind("blur", restrictDecimal);
        // onlyNumber
        $(".onlyNumber").bind("keyup", restrictOnlyNumber);
        $(".onlyNumber").bind("focus", formatSelect);
 
        $(".onlyNumber").bind("blur", restrictOnlyNumber);
        // onlyEnglish
        $(".onlyEnglish").bind("keyup", restrictOnlyEnglish);
        $(".onlyEnglish").bind("focus", formatSelect);
 
        $(".onlyEnglish").bind("blur", restrictOnlyEnglish);
        // onlyEnglishUpper
        $(".onlyEnglishUpper").bind("keyup", restrictOnlyEnglishUpper);
        $(".onlyEnglishUpper").bind("focus", formatSelect);
 
        $(".onlyEnglishUpper").bind("blur", restrictOnlyEnglishUpper);
        // onlyEnglishLower
        $(".onlyEnglishLower").bind("keyup", restrictOnlyEnglishLower);
        $(".onlyEnglishLower").bind("focus", formatSelect);
 
        $(".onlyEnglishLower").bind("blur", restrictOnlyEnglishLower);
        // forCode
        $(".forCode").bind("keyup", restrictForCode);
        $(".forCode").bind("focus", formatSelect);
 
        $(".forCode").bind("blur", restrictForCode);
        // forId
        $(".forId").bind("keyup", restrictForId);
        $(".forId").bind("focus", formatSelect);
 
        $(".forId").bind("blur", restrictForId);
 
        $(".fileExtension").bind("change", restrictFileExtension);
        $(".fileExtensionImg").bind("change", restrictFileExtensionImg);
    });
 



List of Articles
번호 제목 날짜 조회 수
119 jquery 글자 byte, 문자열 byte(바이트) 길이 체크하기 예제 2016.11.17 8833
118 jQuery 기초 ((문자열 추가 .before / .after) (문자열 삭제 .remove / .empty) file 2019.01.16 1084
117 jQuery 기초 (attr()로 두가지 동시에 접근 / 변경) 2019.01.16 1119
116 jQuery 기초 (focus, blur, toggle / mouseenter, mouseleave, mousedown, mouseup, hover) 2019.01.16 1261
115 jQuery 기초 (JQuery - text(), val(), html(), attr(), prop()) 2019.01.16 1055
114 jQuery 기초 (jQuery 달력 (datepicker)) file 2019.01.16 1321
113 jQuery 기초 (Postcodify - 도로명주소 우편번호 검색 프로그램 (코딩 예제) (HTML) / POP UP 버젼) file 2019.01.16 1349
112 jQuery 기초 (Query link url / download (위치, 사용법) // p태그, id, class 접근 / 일반태그 가져오기 / 클릭시 값) 2019.01.16 1079
111 jQuery 기초 (style.css <link> 로 추가하기 / 버튼 클릭시 데이터 삽입) file 2019.01.16 1181
110 jQuery 기초 (txt 파일 가져오기 (load) , 클릭시에 배경색을 변경(json)) file 2019.01.16 3225
109 jQuery 기초 (클릭하면 이미지 변경 / mouseover시 애니메이션 효과주기 / 동적으로 변경) 2019.01.16 1506
108 jQuery 기초 (텍스트 추가 (createElement, createTextNode, appendChild), (html, javascript, jquery) file 2019.01.16 1411
107 jQuery 날짜 비교 (날짜비교) 2016.11.17 10055
106 jquery 뒤로가기 2016.11.17 6511
105 jquery 드래그 앤 드롭 파일 업로드 2019.05.21 3094
104 jquery 디데이 계산 (D-day,Dday) file 2016.11.17 8801
103 jquery 라디오버튼 선택 확인, 체크박스 선택 확인, 셀렉트박스 선택 확인 2016.11.17 7149
102 jQuery 로 원하는 갯수만큼 checkbox 선택하기 2019.01.10 1022
101 jQuery 로 탭메뉴 2019.01.10 938
100 jQuery 로 탭메뉴 보였다 안보였다 맹글기 2019.01.10 1329
Board Pagination Prev 1 2 3 4 5 6 7 8 9 Next
/ 9

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved