HTML input only accept 0-9(Number in English) and ০-৯ (Number in Bengali)?
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">
Here is a working pure HTML-CSS solution. Please note that text can still be entered into the input element but the browser can handle the validation.
It is a trade-off you need to make to support multilingual-input box.
input:invalid {
border: 2px dashed red;
}
input:valid {
border: 2px solid black;
}
<form>
<label for="numberBox">Enter a number</label>
<input type="text" name="numberBox" pattern="[০-৯0-9]" title="Numbers only">
<button>Submit</button>
</form>
To construct the JS regex pattern, first see Bengali Unicode Charts.
09E6
০
BENGALI DIGIT ZERO
09E7১
BENGALI DIGIT ONE
09E8২
BENGALI DIGIT TWO
09E9৩
BENGALI DIGIT THREE
09EA৪
BENGALI DIGIT FOUR
09EB৫
BENGALI DIGIT FIVE
09EC৬
BENGALI DIGIT SIX
09ED৭
BENGALI DIGIT SEVEN
09EE৮
BENGALI DIGIT EIGHT
09EF৯
BENGALI DIGIT NINE
For matching Unicode in JavaScript \uXXXX
notation can be used. To match the wanted range together with \d
for [0-9]
, all can be put into a character class and quantified with +
for one or more.
[\d\u09E6-\u09EF]+
See this demo at regex101 (if using with JS functions, might want to anchor the pattern)
Demo 1: Validation with HTML input pattern attribute
<!-- input pattern test-->
<form>
<input type="text" value="1234567890০১২৩৪৫৬৭৮৯" pattern="[\d\u09E6-\u09EF]+">
<input type="submit" value="check">
</form>
Demo 2: JS validation with RegExp test()
document.getElementById('myform').addEventListener('submit', function(event)
{
if(!/^[\d\u09E6-\u09EF]+$/g.test(document.getElementById('myinput').value))
{
alert('Please enter just Latin and Bengali digits!');
event.preventDefault();
}
});
<form id="myform">
<input id="myinput" type="text">
<input type="submit" value="test">
</form>