Nithin Viswanathan
Nithin Viswanathan

Reputation: 3283

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

Upvotes: 4

Views: 6228

Answers (2)

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

Fiddle

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);
if(userLang!=whatever-you-want){
    alert("only whatever-you-want allowed!!!")
}

Check your language

Upvotes: 1

Moseleyi
Moseleyi

Reputation: 2859

You could use Regex and allow only a-zA-z without any accents or funny letters.

Upvotes: 0

Related Questions