HTML input only accept 0-9(Number in English) and ০-৯ (Number in Bengali)?

Issue

I have a html input field . I want to allow only [0-9] (digits in English) and [০-৯] (digits in Bengali)

If I used type='number' then it only support [0-9] not support [০-৯].

If I used type='text' then it support any type of character

Any Idea please?

Solution

If you want to completely disable the user from inserting not numeric digits, then you should overwrite the keydown event and prevent it if the key isn’t right.
You can also add an event for paste to only allow paste events that only contain the allowed characters.

var allowedKeys = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
  "ARROWRIGHT", "ARROWLEFT", "TAB", "BACKSPACE", "DELETE", "HOME", "END", "০", "১", "২", "৩", "৪", "৫", "৬", "৭", "৮", "৯"
];

if (document.readyState === "complete") onLoad();
else addEventListener("load", onLoad);

function onLoad() {
  document.querySelectorAll("input.numeric").forEach(function(input) {
    input.addEventListener("keydown", onInputKeyDown);
    input.addEventListener("paste", onInputPaste);
  });
}

function onInputKeyDown(event) {
  if (!allowedKeys.includes(event.key.toUpperCase()) && !event.ctrlKey) {
    event.preventDefault();
  }
}

function onInputPaste(event) {
  var clipboardData = event.clipboardData || window.clipboardData;
  if (/^[0-9০-৯]+$/g.test(clipboardData.getData("Text"))) return;
  event.stopPropagation();
  event.preventDefault();
}
<input type="text" class="numeric">

Answered By – nick zoum

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published