Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only all language alphanumeric in jQuery

I am trying to make an input that allows all language letters, English, non-English, etc. except special characters, in total:

Allow:

  • All language alphanumeric
  • CTRL / ALT / SHIFT / SPACE / BACKSPACE / SPACE and etc.

Disallow:

  • Special Characters such _-/!@#$%^&*()+=, 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?

like image 635
Pedram Avatar asked Jun 01 '26 12:06

Pedram


1 Answers

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.

like image 81
Pedram Avatar answered Jun 03 '26 02:06

Pedram