2

I want to check user input that is entering numbers in Persian or not. In the other words it's keyboard language is Persian or English. The field accepts only number. I'm trying something like this:

            document.getElementById("give_me_the_lang").addEventListener("keyup", function() {
            var patt = new RegExp("^[\u06F0-\u06F9]+$");
            if (patt.test(this.value)) {
                document.getElementById("show_lang_in_here").innerHTML = "Persian";                          
            } 
            else {
                 document.getElementById("show_lang_in_here").innerHTML = "english";
Hamid
  • 69
  • 5
  • 1
    Can you add more details about what's not working? – ecraig12345 Mar 17 '19 at 11:48
  • @ecraig12345 I have posted the correct answer – Hamid Mar 17 '19 at 12:06
  • in this case I think the persian characters are the same as english chars, only the system font (os font) is different. – Amin Adel Mar 17 '19 at 12:25
  • NB: They should better be called Latin, not English. – trincot Mar 17 '19 at 12:29
  • @AminAdel .No . the code of English numbers is different from Persian numbers. – Hamid Mar 17 '19 at 12:31
  • True, but FireFox (where Persian digits pose no problem) does not give any clue about the difference: the `value` property of an `input` with `type="number"` attribute will give the Latin string whether it is typed in Persian characters or not. – trincot Mar 17 '19 at 12:38
  • Firefox shows persian Numbers as Persian Numbers but when you click on increase or decrease rows in numbers field it converts it to Latin. @trincot – Hamid Mar 17 '19 at 12:46
  • Yes, indeed. How does that relate to your question? – trincot Mar 17 '19 at 12:50

1 Answers1

1

In my code I have added a parameter to callback function and changed this.value to e.key. and it works correctly.

  document.getElementById("a").addEventListener("keyup", function(e) {
        var patt = new RegExp("^[\u06F0-\u06F9]+$");
        if (patt.test(e.key)) 
            document.getElementById("lang").innerHTML = "Persian";                            
        else 
            document.getElementById("lang").innerHTML = "english";

             })

Second solution:

document.getElementById('a').addEventListener('keypress',function(e){
 if (isPersian(e.charCode))
   document.getElementById("lang").innerHTML='Persian';
 else
   document.getElementById("lang").innerHTML='English';

 });

function isPersian(charCode){
return (charCode >= 1776 && charCode <= 1785) 
}

Unicode

Hamid
  • 69
  • 5
  • relying on which key is pressed is not reliable: input can be pasted in with keys or context menu, or dragged in with the mouse, or entered with another device... – trincot Mar 17 '19 at 12:40
  • Yes, we can use a compound of different events like keypress , onchange or ... to handle it.but my issue was not events, the issue was how Can I test the user inputs – Hamid Mar 17 '19 at 15:15