5

I am using the following code for my validation that only allows letters and numbers and a few allowed characters.

$('input').bind('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9%()#@-_& ]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});

The only problem I am having is that if you copy and paste any un allowed characters then this doesn't prevent it. I know I have seen this done somewhere where it prevents the characters being pasted. Any thoughts?

Suzi Larsen
  • 1,420
  • 5
  • 18
  • 32

2 Answers2

4

You have to do 2 things:

  1. Bind paste event (as is already mentioned above)
  2. Fix your regex that allows characters in the range between @ and _ (all letters and some characters like ^, [... because you did not escape the hyphen, and it creates a range [@-_], which is valid (that is why you are not getting any error), but that is not what you expect.

enter image description here

Here is the fixed code:

$('input').bind('keypress paste', function (event) {
var regex = /^[a-zA-Z0-9%()#@_& -]+$/;
var key = String.fromCharCode(event.charCode || event.which);
if (!regex.test(key)) {
   event.preventDefault();
   return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txt1"/>
vsync
  • 118,978
  • 58
  • 307
  • 400
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    That's great! thanks for the explanation also really helpful – Suzi Larsen Sep 15 '15 at 12:27
  • I wonder why people use "!event.charCode ? event.which : event.charCode" and not "event.charCode ? event.charCode : event.which". Or just "event.which || event.charCode". – gornvix Nov 14 '20 at 19:10
  • @gornvix That was copy/paste of OP code, and 5 years ago when I was completely green in JS. `event.charCode || event.which` works as expected. – Wiktor Stribiżew Nov 14 '20 at 19:24
  • @WiktorStribiżew I couldn't get this to work. Adding "paste" just seems to prevent all pasting into the input box. It seems to me that the whole of the pasted string would need to be validated not just one character. – gornvix Nov 14 '20 at 19:30
1
$("#textareaid").bind("paste", function(e){
    // access the clipboard using the api
    var pastedData = e.originalEvent.clipboardData.getData('text');
    alert(pastedData);
} );

or you can try this way JQuery paste
There is one more way out, that you can do it so with onChange or focusOut events on textbox

Community
  • 1
  • 1
Sunil
  • 919
  • 15
  • 25