I am trying to make an input that allows all language letters, English, non-English, etc. except special characters, in total:
Allow:
CTRL / ALT / SHIFT / SPACE / BACKSPACE / SPACE and etc.Disallow:
_-/!@#$%^&*()+=, etc. like emoji and more.JSFiddle
$('#txtFirstName').on('keydown paste',function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
}
else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) ||
(key >= 35 && key <= 40) || (key >= 65 && key <= 90) ||
(key >= 48 && key <= 57))) {
e.preventDefault();
}
}
});
Well, everything looks great and works fine on desktop, but it is not working on mobile devices like Android or iPhone keyboard, when you use a non-English language keyboard it won't let the user type, so I guess it can't recognize keyboard key code, am I right? Can this issue be fixed? Or can you share another solution for this? Any idea?
I just make this logic reverse, so I wanted to allow alphanumeric in all languages, but it's hard to detect all languages' keyCode unless using a Unicode range, but I write a regular expression to disallow all possible special characters in desktop and mobile phones keyboard.
$('#txtFirstName').on('keydown paste', function(e) {
var pattern = /[`~!@#$%^&*()_|+\-=?;:..’“'"<>,€£¥•،٫؟»«\{\}\[\]\\\/]+/gi;
if (pattern.test($(this).val())) {
alert('not allowed');
$(this).val($(this).val().replace(pattern, ''));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtFirstName" value="">
This solution helped me out this time, but it is not the best solution but I'm still working on it. It's free to add your desired special character to prevent it.
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