user2197029 user2197029 - 1 year ago 59
Javascript Question

JS only alpha numeric and spaces on keyup

I want to limit input to letters numbers and spaces.

And I want it to run on keyup so the user sees other characters being rejected. In other words, I don't want the illegal characters to remain in the field and only get deleted after submission.

I tried this...

$('#custName').keyup(function() {


But as soon as an illegal character is entered, the whole string is deleted.

How can I prevent illegal character as it is entered, while keeping the legal ones?

Answer Source

.match() is returning either:

  • An array of strings (just one in your existing code) in case of a match: in your case -- by luck -- it was coerced to a string, so it seemed to work as expected
  • null in case of no match: that's why the entire input was lost

What you need is more like:

$('#custName').keyup(function() {
    $(this).val($(this).val().replace(/[^\w\s]+/g, ''));

As noticed by Hanlet, another potential issue with this approach is that some browsers will fire a keyup event for non printable characters. So, you may have to filter them with a test on event.keyCode.