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

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of DataStax

AI Agents Made Easy with Langflow

Connect models, vector stores, memory and other AI building blocks with the click of a button to build and deploy AI-powered agents.

Get started for free

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay