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?
You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.
The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.
In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With