Input Mask Using Only Javascript


INTRO

Input mask help user in entering correct input. With mask the input is more readable and the user experience get improve. Suppose you open a form to enter credit card information, if there is not input formatting, you will have to check if you have entered 16 digits or not and with input formating, it will be more visible to see if you have entered 16 digits. 

Without formating:
1234123412341234

With formatting: (More clear)
1234 1234 1234 1234


<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        * {
            box-sizing: border-box;
        }
       
        body {
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: monospace;
            flex-direction: column;
            color: darkblue
        }
       
        .form-label {
            display: block;
            padding-bottom: 5px;
            margin-top: 15px;
        }
       
        .form-control {
            border-radius: 10px;
            border: 2px solid darkblue;
            padding: 15px;
        }
       
        .btn {
            margin-top: 15px;
            background-color: transparent;
            border: 2px solid darkblue;
            color: darkblue;
            padding: 15px;
            font-weight: bold;
            border-radius: 15px;
            display: block;
            width: 100%;
        }
       
        .btn:hover {
            background-color: darkblue;
            border: 3px solid white;
            color: white;
        }
       
        #result {
            margin-top: 15px;
        }
    </style>
</head>

<body>
    <h1>Input Mask Using Only JS</h1>
    <div class="form-group">
        <label for="credit-card" class="form-label">Credit Card Mask Using Regex</label>
        <input type="text" class="form-control credit-card" value="" placeholder="Enter 16 Digits card number">
    </div>
    <div class="form-group">
        <label for="credit-card-2" class="form-label">Credit Card Mask Using Mask</label>
        <input type="text" class="form-control credit-card-2" value="" placeholder="Enter 16 Digits card number">
    </div>
    <div class="form-group">
        <label for="phone-number" class="form-label">Phone</label>
        <input type="text" class="form-control phone-number" value="" placeholder="Enter 10 Digits phone number">
    </div>
    <div class="form-group">
        <button class="btn" onclick="getResult()">Get Result</button>
    </div>
    <div class="form-group">
        <div id="result"></div>
    </div>

    <script>
        let creditCardInput = document.querySelector(".credit-card");

        class InputMask {

            getUnformattedValue(selector) {
                let input = document.querySelector(`${selector}`);
                let del = input.getAttribute("data-delimiter");
                return input.value.replaceAll(del, "");

            }

            convertMaskToReg(mask) {
                mask = mask.replaceAll("9", "\\d");
                mask = mask.replaceAll("-", ")(");
                let maskFinal = new RegExp("^(" + mask + ")+$");
                return maskFinal;
            }

            // selector #phoneno, .phoneno
            // mask (no of characters using 9 digit) "9999", "999"
            //useReg = true if you want to use regex instead of 9999 mask
            // regex /^(\d{3})(\d{0,3})(\d{0,4})+$/

            formatInputAsFixedMask(selector, mask = "999-999-9999", parts = 3, delimitor = "-", useReg = false) {
                let inputField = document.querySelector(`${selector}`);
                let inputFieldValue = this.getUnformattedValue(selector);
                inputField.setAttribute("data-delimiter", delimitor);
                if (!useReg) {
                    mask = this.convertMaskToReg(mask);
                }
                let matches = inputFieldValue.match(mask);
                let result = "";
                if (matches) {
                    for (let i = 1; i <= parts; i++) {
                        result += matches[i] ? matches[i] + (matches[i + 1] ? delimitor : "") : "";
                    }
                    inputField.value = result;
                }
            }

        }

        function attachMultipleEvents(selector, eventsArr, callback) {
            let ele = document.querySelector(`${selector}`);
            eventsArr.forEach(eve => {
                ele.addEventListener(eve, () => {
                    callback();
                });
            })
        }

        let inputMask = new InputMask();

        attachMultipleEvents(".phone-number", ['blur', 'keyup'], () => {
            inputMask.formatInputAsFixedMask(".phone-number", "999-999-9999", 4, ' ');
        })

        attachMultipleEvents(".credit-card", ['blur', 'keyup'], () => {
            inputMask.formatInputAsFixedMask(".credit-card", /^(\d{4})(\d{4})(\d{4})(\d{4})+$/, 4, '-', true);
        })

        attachMultipleEvents(".credit-card-2", ['blur', 'keyup'], () => {
            inputMask.formatInputAsFixedMask(".credit-card-2", "9999-9999-9999-9999", 4, '-', false);
        })


        function getResult() {
            let html = "Phone number is : " + inputMask.getUnformattedValue(".phone-number") + "<br>";
            html += "Credit card number is : " + inputMask.getUnformattedValue(".credit-card") + "<br>";
            document.querySelector("#result").innerHTML = html;
        }
    </script>
</body>

</html>



See the Pen Untitled by Muhammad Habib (@mhabib555) on CodePen.

Comments

Popular posts from this blog

JS-QR Generator

Input Mask Using Libraries

PHP -Sending Email from Localhost (XAMPP) Using SendinBlue