What is the best way to use Javascript to format an account name and/or sort code?

I am posting this question with my answer so far but would like to invite other solutions as I am not 100% sure about mine.

It will:

  • Automatically place the dashes in the right place so the user only has to enter the digits.
  • Can be any size. You can set a maxlength attribute on your input and it will continue to apply dashes intil it runs out of space. It will default to 8 characters max
  • Allowsuser to delete digits without the need to delete the dashes too.

Why am I posting a this? I could not find the answer myself on StackOverflow and when you search this question on Google, it keeps returning a PHP answer for StackOverflow instead! There are even answers in there for Javascript. Hopefully this question can produce other solutions too!

How does it work?

This is designed to work with a real-time input.

  • It works out the maximum length
  • It captures the event and works out if the delete key was pressed
  • The 'regex' part is saying to replace ever 2nd character with itself plus a dash.
  • The next line first replaces anything that's not a number, then uses the regex to inject dashes and finally the string is sliced to remove any trailing slash

You would apply this function to your onkeyup or onpaste events, passing 'this' in.

function checkSortCode(el,ev){
      var len = el.maxLength || 8;
            ev = ev || window.event;
            if(ev.keyCode == 8 && el.value.slice(-1) == "-"){
                el.value = el.value.slice(0,-1);
            } else {
                var regex = new RegExp("(\\S{" + (2 - 1) + "}\\S)", "g");
                el.value = el.value.replace(/[^0-9]/g,"").replace(regex,("$1"+"-")).slice(0,len);
            }
        }
.sortcode::placeholder{color:#eeeeee;}
body{font-family:arial,sans-serif;font-size:1.4em;}
input{font-size:1.4em;}
<label>Sort Code</label><br>
<input type="text" name="sortcode" onkeyup="checkSortCode(this,event)" onpaste="checkSortCode(this,event)" class="sortcode" size="8" maxlength="8" placeholder="00-00-00" />

Ideally, I wanted it to show the 00-00-00 format all the time and then the user would fill it in but have padded zeros where they hadn't. That's not easy as the cursor wants to go to the end of the input.

Answer №1

If you're searching for a solution, it's known as Input Masking. While you can create your own implementation, it's advisable to utilize a library to manage the input value separate from the mask.

Below is a demonstration using plain JavaScript, though it may seem a bit clumsy.

<html>
<body>

    <input id="input">

    <script>
        const pattern = '00-00-00-00'
        const patternRegex = /^[0-9]{2}\-[0-9]{2}\-[0-9]{2}\-[0-9]{2}$/
        const separator = '-'

        /* fills current value with the pattern (filled with 0) */
        const fill = value => {
            return `${value}${pattern.substring(value.length)}`
        }

        /* format the input on keyup */
        const format = event => {
        
            /* format only the input at cursor position (ignores filled pattern) */
            const position = event.target.selectionStart
            const value = event.target.value.substring(0, position)

            /* revert invalid inputs */
            if (!patternRegex.test(fill(value))) {
                event.target.value = event.target.value.substring(0, position - 1)
                return
            }

            /* update target value to include pattern and restore cursor position */
            event.target.value = fill(value)
            const newPosition = event.target.value[position] === separator ? position + 1 : position
            event.target.setSelectionRange(newPosition, newPosition)
        }

        const input = document.getElementById('input')
        input.addEventListener('keyup', format)
    </script>

</body>
</html>

If you want to explore other implementations, you can visit: https://css-tricks.com/input-masking/

The slight awkwardness in the implementation is due to formatting the input after a change occurs. By using a library (or React), you can manage the input value before rendering it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble receiving JSON data from jQuery method

I am encountering difficulty in correctly capturing a JSON object within a function that is executed when the page loads. My goal is to capture this object so that I can later POST it to another page based on user action. This code is being run on Windows ...

Creating JSON from identical user interface components

I have created a form similar to this one: https://jsfiddle.net/6vocc2yn/ that generates a JSON output like below: { "List": [ { "Id": 10, "Name": "SDB_SOLOCHALLENGE_CHALLENGE_DESC_10", "email": "<a href="/cdn-cgi/l/email-pr ...

ajax is unable to decode a JSON string from a GET request

Currently, I am leveraging angularjs to retrieve userId, userTitle, and userComment from a form. These values are then sent to a PHP page from the controller for communication with a server. Everything works well when sending integers, but I face an issue ...

When running scripts, Protractor is unable to perform a click action in Safari, even though it works perfectly in

Currently, I am in the process of developing an angular application and utilizing directconnect for Chrome and Firefox. All my test scripts are functioning as expected, however, a new requirement has been introduced to run these same tests on Safari. To ...

Embedding Array into Mongodb is an efficient way to store and

Whenever I attempt to store array data within MongoDB using the query below, it always shows a success message without actually storing any data in an empty array inside MongoDB. My goal is to successfully store array data inside MongoDB as shown in the f ...

The functionality of saving a file using the jsPDF method is not functioning properly

After dedicating four days to resolving a seemingly straightforward task that involved the jsPDF library, I found myself faced with a challenge. My goal was to save a file using this library, not just print it like I had successfully done before. This is ...

Toggle the div's visibility to fade in and out once more

Apologies if this is a simple issue to resolve. My goal is to create a div that, when selected, will be replaced by another div with the option to switch back to the original div when "back" is clicked. This is my current progress: $(document).ready( ...

Displaying an interactive 2D floorplan in a web browser with the use of html5 and javascript

In the process of updating my old Flash viewer, I am looking to display interactive 2D floorplans exported from AutoCAD. Currently, I convert the AutoCAD files into XML files containing the X and Y coordinates of the various elements on the floorplan such ...

What is the best method for opening .xls files using ExcelJS?

I am facing an issue with accessing a .xls file using the ExcelJS library. Interestingly, there are no issues when it comes to reading .xlsx files. Previously, I relied solely on the xlsx js library and never encountered any problems while accessing .xls f ...

Experimenting with ES6 modules using Mocha

Recently, I was given a new project at work that involves using raw native imports/exports in code (compatible only with the latest browsers). The project is being worked on by consultants, and although I cannot make significant changes to their work, I am ...

Vue JS - Troubleshooting Checkbox Validation Error During Form Submission

When a user fills out my registration form, there is a checkbox to confirm acceptance of the terms and conditions. Currently, the validation error for this checkbox appears immediately upon hitting submit, even though the checkbox starts as unchecked. The ...

Dealing with customized protocol responses in JavaScript

My web server is set up to return a response like: HTTP/1.1 302 Found message://ActualMessage While this setup works seamlessly for UI clients like Android and iOS, I'm faced with the challenge of handling this case on a web browser. For instance, ...

Is it possible to list bash/sh files as dependencies in package.json?

Currently, I have a bash script named publish.sh that I use for publishing modules to npm. Since I am constantly adjusting this script, I find myself needing to update every copy of it in each npm module I manage. Is there a method to include this bash sc ...

Error injecting angular.bootstrap in Angular 1.6.5 version

I have a MeanJS.org skeleton app that I've transformed into hapi-js from express, switched to postgres from mongo, and incorporated OAUTH for authentication (mainly because I liked the server/client module folder structure - haha). Everything seems t ...

Tips for safeguarding the security of my PHP API when accessed through Ajax using OAuth2

I've developed a cross-origin ajax application that utilizes some personal APIs I created. Now, I'm looking to enhance the security measures so only my application has access to the API. After researching, I came across OAuth2 at OAuth2. I foll ...

Can HTML text areas be designed to adjust their width automatically, as well as their height?

Among the numerous StackOverflow examples showcasing an auto-height Textarea, one noteworthy example can be found here: <textarea oninput="auto_grow(this)"></textarea> textarea { resize: none; overflow: hidden; min-heig ...

What is the best way to display a component with multiple pieces of content?

I have a tool that generates card components, extracting data from a const array and displaying it in a table format within a card UI component. I am looking to add an ADD button inside each card to open a modal with input fields. However, the issue is tha ...

What is the best way to incorporate variables into a text file using ajax?

I am having an issue with my code. I have written a script that allows users to draw an image on canvas and then extract pixel values from the clicked location, writing them into a text file using ajax. However, I am facing problems with my onclick and a ...

Issue with Orgchart JS: The requested resource does not have the 'Access-Control-Allow-Origin' header present

Currently, I am developing a program to create organization charts using orgchart.js and simple PHP. This project does not involve any frameworks, but unfortunately, I encountered the following error: CORS policy is blocking access to XMLHttpRequest at & ...

jsGrid is failing to load within a Vue application that is utilizing static data

Struggling to implement jsGrid for a basic table with header sorting in my Javascript and Vue application. Having trouble loading the sample code with various components spread across different files. Here are the relevant parts: HTML (symbol-container is ...