재우니의 블로그

input box 에서 keydown keyup mousedown mouseup select contextmenu drop 관련 이벤트들을 적용하여 정규화를 사용해서 차단한 방법입니다.

 

테스트는 https://jsfiddle.net/emkey08/tvx5e7q3 사이트에서 확인이 가능합니다.

 

<h2>jQuery input filter showcase</h2>
<p>This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the
    cursor position, all keyboard layouts and <a href="https://caniuse.com/#search=oninput" target="_blank">all browsers
        since IE 9</a>.</p>
<p>There is also a <a href="https://jsfiddle.net/emkey08/zgvtjc51" target="_blank">pure JavaScript version</a> of this
    (without jQuery).</p>
<table>
    <tr>
        <td>Integer (both positive and negative):</td>
        <td><input id="intTextBox"></td>
    </tr>
    <tr>
        <td>Integer (positive only):</td>
        <td><input id="uintTextBox"></td>
    </tr>
    <tr>
        <td>Integer (positive and &lt;= 500):</td>
        <td><input id="intLimitTextBox"></td>
    </tr>
    <tr>
        <td>Floating point (use . or , as decimal separator):</td>
        <td><input id="floatTextBox"></td>
    </tr>
    <tr>
        <td>Currency (at most two decimal places):</td>
        <td><input id="currencyTextBox"></td>
    </tr>
    <tr>
        <td>Hexadecimal:</td>
        <td><input id="hexTextBox"></td>
    </tr>
</table>


<script>

    // Restricts input for each element in the set of matched elements to the given inputFilter.
    (function ($) {
        $.fn.inputFilter = function (inputFilter) {
            return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function () {
                if (inputFilter(this.value)) {
                    this.oldValue = this.value;
                    this.oldSelectionStart = this.selectionStart;
                    this.oldSelectionEnd = this.selectionEnd;
                } else if (this.hasOwnProperty("oldValue")) {
                    this.value = this.oldValue;
                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                }
            });
        };
    }(jQuery));


    // Install input filters.
    $("#intTextBox").inputFilter(function (value) { return /^-?\d*$/.test(value); });
    $("#uintTextBox").inputFilter(function (value) { return /^\d*$/.test(value); });
    $("#intLimitTextBox").inputFilter(function (value) { return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 500); });
    $("#floatTextBox").inputFilter(function (value) { return /^-?\d*[.,]?\d*$/.test(value); });
    $("#currencyTextBox").inputFilter(function (value) { return /^-?\d*[.,]?\d$/.test(value); });
    $("#hexTextBox").inputFilter(function (value) { return /^[0-9a-f]*$/i.test(value); });

</script>

 

text 타입에 숫자만 받는 스크립트 구현하기

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">

 

https://jsfiddle.net/emkey08/tvx5e7q3

 

Input filter showcase - JSFiddle - Code Playground

 

jsfiddle.net