An input mask will format an input value to better represent the data.
- credit card:
4455-4455-1234-1234
- SSN:
123-12-1234
- phone number (NA):
123-123-1234
First, extract the pattern by finding the indexes of the spaces.
function getPattern(pattern) {
dashIdxs = [];
pattern.split("").forEach((char, idx) => {
if (char !== "-") {
return;
}
dashIdxs.push(idx);
});
return dashIdxs;
}
Two additional functions as handlers for oninput
and keydown
events. value
is the our masked value.
function onkeydown({ key }) {
if (key === "Backspace" && dashIdxs.includes(value.length - 1)) {
value = value.slice(0, -1);
}
}
function oninput({ currentTarget }) {
value = currentTarget.value;
if (dashIdxs.includes(value.length)) {
value += "-";
}
}
A working example built with Mithril.js.
This is a pretty trivial implementation, and not production ready. It would at least need to support copy/paste.
cover image: @theonlynoonan - https://unsplash.com/photos/QM_LE41VJJ4
Top comments (0)