Skip to content

Instantly share code, notes, and snippets.

@muzfr7
Last active May 31, 2023 11:37
Show Gist options
  • Save muzfr7/faf97fccf267504916a5f557b166118d to your computer and use it in GitHub Desktop.
Save muzfr7/faf97fccf267504916a5f557b166118d to your computer and use it in GitHub Desktop.
Restrict user from typing Non-Arabic characters in input fields using Javascript / JQuery
<html>
<head></head>
<body>
<form>
<input id="candidate_firstname" name="firstname" required="required" class="gui-input" dir="rtl" type="text" />
<input id="candidate_lastname" name="lastname" required="required" class="gui-input" dir="rtl" type="text" />
</form>
<script type="text/javascript">
function restrictInputOtherThanArabic($field)
{
// Arabic characters fall in the Unicode range 0600 - 06FF
var arabicCharUnicodeRange = /[\u0600-\u06FF]/;
$field.bind("keypress", function(event)
{
var key = event.which;
// 0 = numpad
// 8 = backspace
// 32 = space
if (key==8 || key==0 || key === 32)
{
return true;
}
var str = String.fromCharCode(key);
if ( arabicCharUnicodeRange.test(str) )
{
return true;
}
return false;
});
}
jQuery(document).ready(function() {
// allow arabic characters only for following fields
restrictInputOtherThanArabic($('#candidate_firstname'));
restrictInputOtherThanArabic($('#candidate_lastname'));
});
</script>
</body>
</html>
@AhmedMeshaal
Copy link

thanks.. very helpful

@hassanbouaakab
Copy link

Thanks for the function, maybe you can disable pasting none Arabic text too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment