Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS only alpha numeric and spaces on keyup

Tags:

javascript

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() {
    $(this).val($(this).val().match(/^[\w\s]+$/));
});

Fiddle

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?

like image 440
webguy Avatar asked Mar 12 '23 13:03

webguy


2 Answers

.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.

like image 60
Arnauld Avatar answered Mar 20 '23 08:03

Arnauld


Validation for name // will accept alphabets and space and backspace

$('.nameonly').on('keydown', function(e){
    if ((e.which < 65 &&  e.which != 32 && e.which != 8) || e.which > 90 ) {
        return false;
    }
});
like image 36
Jathin Valappil Avatar answered Mar 20 '23 09:03

Jathin Valappil