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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.