Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable onpaste only for alphabetic letters

I have got a task to disable the textbox from pasting.Only the alphabetic characters must be allow to paste. My code is

<b>Name</b>
<input type="text" id="name" onpaste="return false"/>

By giving onpaste="return false" no values are pasted. How can I solve this problem?

like image 738
Nithin Viswanathan Avatar asked Mar 27 '13 12:03

Nithin Viswanathan


2 Answers

Try this code

$(".alphabetOnly").bind('paste', function(e) {
  var self = this;
  setTimeout(function(e) {
    var val = $(self).val();
    if (val != '0') {
      if (val.match(/^[0-9]+$/) != null) {
        $(".alphabetOnly").val("");
      }
      $(this).val(val);
    }
  }, 0);
});

I have updated the code here

like image 170
Okky Avatar answered Sep 20 '22 16:09

Okky


Made some mistakes before, this is working:

$('#name').bind('paste', function(){
    var self = this;
    setTimeout(function() {
        if(!/^[a-zA-Z]+$/.test($(self).val()))
            $(self).val('');
    }, 0);    
});

You have to remove the onpaste="return false" from your html!

A working example can be found here: JS Fiddle

like image 41
Rob Avatar answered Sep 18 '22 16:09

Rob