How to enable onpaste for letter letters only

I have a task to disconnect a text field from an insert. Only alphabetic characters should be allowed for insertion. My code

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

By providing onpaste = "return false", no values ​​are inserted. How can I solve this problem?

+6
source share
4 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 updated the code here

+7
source

Made some mistakes before, this works:

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

You need to remove onpaste="return false" from html!

A working example can be found here: JS Fiddle

+2
source

This code restricts the insertion of characters other than numbers in the input field. When I insert a value into the input field, I check the value with a regular expression, if the condition is true, the value will be set, or else I will empty the input value. In my case, I had to limit other characters besides numbers, you can change the regex based on your requirement

 $(".numbersOnly").bind('paste', function(e) { var self = this; setTimeout(function(e) { var val = $(self).val(); if (val != '0') { var regx = new RegExp(/^[0-9]+$/); if (!regx.test(val)) { $(".numbersOnly").val(""); } $(this).val(val); } }, 0); }); 
+2
source

Place the function call inside your value as an insert. Then non-alphabetic characters are eliminated inside this function.

See this question for more details.

0
source

All Articles