Reputation: 352
I have an application that accepts input in two languages (English and Arabic) I'm validating the input textbox , the validation logic is not the same for English and Arabic, so I need to know what is the language the user is typing
all the solutions I came across determined the default language for the system and browser but nothing I found helped me determining the current input language
Upvotes: 3
Views: 4323
Reputation: 352
ok here is the solution that worked for me. Note that in my application I know for sure the input language will be one of two Languages either input is English Or Arabic so here what I did
var msgText = entered message text;
var textLength = msgText.length; // entered message length
var isEnglish = true;
for (var index = 0; index <= textLength; index = index + 1) {
if (msgText.charCodeAt(index) > 160) {
//Not English
isEnglish=false;
break;
}
}
in the previous Example that is what I Needed , if a single character is Arabic the whole text should be validated as Arabic so I added a variable isEnglish = true by default and will only be changed if a character in the string is not English I iterated the characters in the string using the charCodeAt(index) which returns the ISO Latin-1 Character Number . using the table in the this page I was able to decide that the maximum number in this set that represents English chars was 160 and
Upvotes: 1
Reputation: 78971
You can do this using Google's AJAX Language API
var content = "your text";
google.language.detect(content, function(result) {
if (!result.error) {
var language = 'unknown';
for (lang in google.language.Languages) {
if (google.language.Languages[lang] == result.language) {
language = lang;
break;
}
}
// Now use the variable `language`
}
});
Upvotes: 0
Reputation: 18018
You can use ActiveXObject to send an input key say 'a' and read its unicode/ascii value. If its 97 its English else not. Check out this question :
Get the current keyboard layout language in JavaScript
Upvotes: 0