user1543784
user1543784

Reputation: 363

How to allow only numbers (even when copy-pasted) in input text field using jQuery?

I am using this jQuery code to allow only numbers to be entered in input text field.

jQuery(document).ready(function() {     
    jQuery( '.only_numbers' ).keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            ((e.keyCode === 65) && (e.ctrlKey === true || e.metaKey === true)) || 
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});

This works fine, except one small problem. It does not allow anything to be pasted in the field. How can I allow user to paste a string in the field, only if the string contains all numeric characters?

Also, it will be awesome if I could do the same for input text fields allowing only alphabets.

Upvotes: 8

Views: 32424

Answers (8)

Saroj
Saroj

Reputation: 1373

Your HTML

 <input type='text' />

Your Jquery

 $('input').on('paste', function (event) {
  if (event.originalEvent.clipboardData.getData('Text').match(/[^\d]/)) {
    event.preventDefault();
  }
});

$("input").on("keypress",function(event){
                if(event.which < 48 || event.which >58){
                    return false;
                }
            });

Working codepen https://codepen.io/anon/pen/pwEXyg

Upvotes: 12

Zze
Zze

Reputation: 18805

You can use regex to achieve this.

Numbers only.

function process(input){
  let value = input.value;
  let numbers = value.replace(/[^0-9]/g, "");
  input.value = numbers;
}
<input type="text" oninput="process(this)">

Letters only.

function process(input){
  let value = input.value;
  let letters = value.replace(/[0-9]/g, "");
  input.value = letters;
}
<input type="text" oninput="process(this)">

Upvotes: 17

Ananth Cool
Ananth Cool

Reputation: 135

Restrict other keys using keyboard event

//numbers, delete, backspace, arrows        
var validKeyCodes = [8, 9, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
        $("Selectors").on("keydown", function (e) {
            if (!($.inarray(e.keycode, validkeycodes) >= 0))
                e.preventDefault();
        });

Upvotes: 0

Kenneth Tobias
Kenneth Tobias

Reputation: 1

Actually, you only need a "pattern" attribute.

<input type="text" pattern="[\d\t.]+" formnovalidate="false "/>

Upvotes: 0

Kenneth Tobias
Kenneth Tobias

Reputation: 1

Here is my solution which is faster than JS.

<input type="text" pattern="[\d+\t.]+" formnovalidate="false"/>

Upvotes: 0

Manish
Manish

Reputation: 5066

Why are you making things so complicated. You can just make the input type='number' and that would serve your purpose you don't need jQuery for that. It wont allows alphabets except e for exponential numbers and when you copy paste to this it will just paste the numbers from the copied string to the textbox and e as well.

Also below is the code that will allow only alphabets in a textbox. And also the code that allows only numbers in a textbox of type=text.

function onlyAlphabets(event) {
  //allows only alphabets in a textbox
  if (event.type == "paste") {
    var clipboardData = event.clipboardData || window.clipboardData;
    var pastedData = clipboardData.getData('Text');
    if (isNaN(pastedData)) {
      return;

    } else {
      event.prevetDefault();
    }
  }
  var charCode = event.which;
  if (!(charCode >= 65 && charCode <= 120) && (charCode != 32 && charCode != 0) && charCode != 8 && (event.keyCode >= 96 && event.keyCode <= 105)) {
    event.preventDefault();
  }
}

function onlyNumbers(event) {
  if (event.type == "paste") {
    var clipboardData = event.clipboardData || window.clipboardData;
    var pastedData = clipboardData.getData('Text');
    if (isNaN(pastedData)) {
      event.preventDefault();

    } else {
      return;
    }
  }
  var keyCode = event.keyCode || event.which;
  if (keyCode >= 96 && keyCode <= 105) {
    // Numpad keys
    keyCode -= 48;
  }
  var charValue = String.fromCharCode(keyCode);
  if (isNaN(parseInt(charValue)) && event.keyCode != 8) {
    event.preventDefault();
  }
}
Number Only With Type=Number:
<input type="number" name="quantity" min="1" max="5">
<br> Number Only With Type=Text:
<input type="text" name="quantity" min="1" max="5" onkeydown="onlyNumbers(event)" onpaste="onlyNumbers(event)">
<br>Aplhabets Only:
<input type="text" onkeydown="onlyAlphabets(event)" onpaste="onlyAlphabets(event)"/>

Update

Added code to allow only numbers in an input of type=text. And also will work in Firefox and IE as well

Hope it helps :)

Upvotes: 3

Rudraksh Pathak
Rudraksh Pathak

Reputation: 898

Try this, it will restrict typing alphabets and won't let you paste it either.

$(document).ready(function(){
    $("#test").on("keypress",function(event){
        if(event.which <= 48 || event.which >=57){
            event.preventDefault();
        }
    });
    
    $("#test").on("change",function(event){
        $value = $("#test").val();
        if(isNaN($value)){
          $("#test").val('');
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">

Upvotes: 2

Icewine
Icewine

Reputation: 1851

If, you wanted to do it by skipping the JS you could just set your input type="number". Though it does not work for alphabet...

Upvotes: 2

Related Questions