Niths Niths - 2 years ago 73
jQuery Question

Restricting Multilanguages for input field

I have got a task to restrict the input field from non English languages.Only English should be enter on the field.

MY textbox is

<input type="text"/>

The function is

$(document).on("keypress", "input[type='text'] function (event) {
return suppressNonEng(event);

function suppressNonEng(EventKey) {
var key = EventKey.which || EventKey.keyCode;
if (key > 128) { sefAlert("Only English is allowed"); return false; }
else { return true; }

Its worked in the case of Chinese,Greek and some other also.But in the case of Spanish,French, its not working because the same ASCII character is used in the English and French. Is there any solution for this problem?please help

Answer Source


Its pretty simple. You need to match every character entered with a regex that checks whether the character entered is from the English alphabet, or not.

$("#mytextbox").on("keypress", function(event) {
    var englishAlphabetAndWhiteSpace = /[A-Za-z ]/g;
    var key = String.fromCharCode(event.which);
    if (englishAlphabetAndWhiteSpace.test(key)) {
        return true;
    alert ("this is not in English");//put any message here!!!

After your comments:

Every key on the keyboard has a keycode. So when you press a key like E, the computer will interpret it as a keycode (69, in this case). It's difficult to make the computer understand the difference between French E or English E.

If you dont want to alert the user, just replace the alert with return false;.

If you need to detect the browser language:

Use this:

var userLang = navigator.language || navigator.userLanguage; 
alert ("The language you are using is: " + userLang);
    alert("only whatever-you-want allowed!!!")

Check your language

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download