DEV Community

Cover image for Simple Input Mask
Kevin Cameron
Kevin Cameron

Posted on

5 3

Simple Input Mask

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series