user4221591
user4221591

Reputation: 2180

disable hindi characters as input for input type number

I've a textbox of type number. I've disabled text input via javascript. But the text box is accepting hindi strings and numbers. When the user gives hindi number as input, it is converted to english in code behind page. But the hindi characters are creating problem, I should prevent hindi input characters.

<input type="number" id="txtWard" onkeypress="return numberOnly(event)" required="required" runat="server" min="0" max="8" />

javascript code

function numberOnly(evt) {
    var charCode = (evt.which) ? evt.which : window.event.keyCode;

    if (charCode <= 13) {
        return true;
    }
    else {
        var keyChar = String.fromCharCode(charCode);
        var re = /[0-9]/
        return re.test(keyChar);
    }
}

Example of hindi text "हिन्दी" and numbers "१ २ ३ ४". The textbox should not accept hindi text. How could I disable hindi strings also?

Upvotes: 0

Views: 1787

Answers (2)

Pedram
Pedram

Reputation: 16595

So, I used Google input tools for testing with Hindi characters, and for me work good, if you want to allow only number, you can use /\D/ to allow only digit, by this you don't need to detect key number, try below code:

function numberOnly(e) {
  if (/\D/g.test(e.value)) {
    e.value = e.value.replace(/\D/g, '');
  }
}
<input type="number" id="txtWard" onkeypress="return numberOnly(this)" required="required" runat="server" min="0" max="8" />

Upvotes: 0

Koja
Koja

Reputation: 900

I don't think your problem has to do with specific characters. Your problem is that the validation is only ran if a character is entered manually, and not if it is e.g. pasted from the clipboard. If you use ASP.NET, you can use built-in validation in addition to your current JS validation, an example can be found here: https://stackoverflow.com/a/1427777/5098386

edit: or if you want to keep it on the JS, just use onchange event instead of onkeypress.

Upvotes: 1

Related Questions