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?
.match()
is returning either:
null
in case of no match: that's why the entire input was lostWhat 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
.
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With