JavaScript regex + jQuery to match alert if arabic characters in input textbox
This fiddle shows how to use a regular expression to not allow only arabic letters in an input field
For the original post, go here:
http://www.leniel.net/2012/10/javascript-regex-jquery-to-match-only-english-characters-in-input-textbox.html
HTML
<input id="mytextbox" style="width:300px" placeholder="Only non russian letters are allowed here..."> JavaScript regex + jQuery to match on
CSS
фывфывфывффывф
фывфывф
JavaScript
f$("#mytextbox").on("keypress", function(event) {
// Disallow anything not matching the regex pattern (A to Z uppercase, a to z lowercase and white space)
// For more on JavaScript Regular Expressions, look here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
var arabicAlphabet = /[\u0600-\u06ff]|[\u0750-\u077f]|[\ufb50-\ufc3f]|[\ufe70-\ufefc]/g;
//var cyrillicAlphabet = /[\u0400-\u04ff]|[\u0500-\u052f]|[\u2de0-\u2dff]|[\ua640-\ua69f]|[\u1d2b-\u1d78]/g;
// Retrieving the key from the char code passed in event.which
// For more info on even.which, look here: http://stackoverflow.com/q/3050984/114029
var key = String.fromCharCode(event.which);
//alert(event.keyCode);
// For the keyCodes, look here: http://stackoverflow.com/a/3781360/114029
// keyCode == 8 is backspace
// keyCode == 37 is left arrow
// keyCode == 39 is right arrow
// englishAlphabetAndWhiteSpace.test(key) does the matching, that is, test the key just typed against the regex pattern
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || !cyrillicAlphabet.test(key)) {
return true;
}
// If we got this far, just return false because a disallowed key was typed.
alert("Russian text detected - Please enter your details in english")
return false;
});
$('#mytextbox').on("paste",function(e)
{
e.preventDefault();
});