Advertisement
  1. Web Design
  2. UX/UI
  3. Forms

Form Design: How to Automatically Format User Input

Scroll to top

In this tutorial you’ll learn how to format, real time, user input in a form field. As a user types something into an input field the value will be adjusted automatically, adding things like punctuation and dashes, trimming spaces, removing unexpected characters, and changing the word-casing.

This approach can greatly facilitate users when entering form data. It makes the process easier, minimizes errors, gives feedback, and generally improves the user experience.

We’ll explore two examples, using jQuery for the APIs, methods, and utilities to make writing the code more convenient and intuitive. Having a basic understanding of jQuery will help, though you should be able to understand what’s going on even if you don’t. Let’s begin!

1. How to Format a Currency Value

Check out the starter pen, fork it, and follow along. It contains a text input field, with some styles to make it presentable. The JS tab is empty, but already has jQuery added to the <head> and is ready to go!

And as you can see below, our input expects a sum of money. This kind of input field may typically be found in a banking, payment processor, or currency exchange form.

There are two issues that I’ve frequently encountered with this type of input:

  • Some people (like me) have a hard time distinguishing between 1000000 and 10000000 without the thousand separator added. Is it one million or ten million?
  • Some people add the thousand separator by themselves, which is technically not necessary. This could ultimately invalidate the value, leading to an error being thrown.

Begin JavaScript

To begin formatting the input value, we select the input element, assigning the result to a variable.

1
var $form = $( "#form" );
2
var $input = $form.find( "input" );

Keyup

Then we attach the keyup event to our input; firing a function when the user presses then releases a keyboard key.

1
$input.on( "keyup", function( event ) {
2
3
	// 1.

4
	var selection = window.getSelection().toString();
5
	if ( selection !== '' ) {
6
		return;
7
	}
8
9
	// 2.

10
	if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
11
		return;
12
	}
13
14
} );

Within this function we also add a few line of code. These additional lines prevent the function from running when the user 

  1. makes a selection within the input
  2. or presses the arrow keys on the keyboard.

In both these scenarios no new character is added, so it isn’t necessary to continue executing the function.

Main Function

Next, still within our function, below the section preventing arrow keys from executing the function, we add the following. This is the main function that will format the value.

1
    // 1

2
    var $this = $( this );
3
    var input = $this.val();
4
5
    // 2

6
    var input = input.replace(/[\D\s\._\-]+/g, "");
7
	
8
    // 3

9
    input = input ? parseInt( input, 10 ) : 0;
10
11
    // 4

12
    $this.val( function() {
13
        return ( input === 0 ) ? "" : input.toLocaleString( "en-US" );
14
    } );

These lines carry out the following:

  1. Retrieve the value from the input.
  2. Sanitize the value using RegEx by removing unnecessary characters such as spaces, underscores, dashes, and letters.
  3. Deploy parseInt() function to make sure the value is an integer (a round number).
  4. Add the thousand separator with the toLocaleString() function, then pass the sanitised value back to the input element.

Note: The separator can either be , or . depending on the country code passed in the toLocaleString() function. German, de-DE, and Indonesia, id-ID, for example, use . instead of ,.

End Result

Give the demo a try!

As you are typing on the input, you should find that letters and special characters (like dash and dot) will be removed immediately. You will only be able to input a number. The thousand separator will automatically be added.

2. How to Format a License Number

Another type of input where it makes sense to apply this approach is the “License Number” input. The Envato Market license number or purchase code, for example, is 36 characters long and comprises letters, numbers, and a few dashes. Entering it correctly on authors’ websites is vital if you need support!

Envato purchase codeEnvato purchase codeEnvato purchase code
From Where Is My Purchase Code?

You may also find this kind of input in a premium WordPress theme or plugin, where you have to input a license code to receive updates or use particular features.

In this second example, we have created an input field with a placeholder text hinting at the license number format. And as you can see below, the license number comprises 32 characters with several dashes in between, and each character should be capitalized.

Starter Pen

Here’s the starter pen; fork it and follow along!

Main Function

We’ll share the same codebase as our first example, except for the main function.

1
// 1

2
var $this = $(this);
3
var input = $this.val();
4
5
// 2

6
input = input.replace(/[\W\s\._\-]+/g, '');
7
8
// 3

9
var split = 4;
10
var chunk = [];
11
12
for (var i = 0, len = input.length; i < len; i += split) {
13
	split = ( i >= 8 && i <= 16 ) ? 4 : 8;
14
	chunk.push( input.substr( i, split ) );
15
}
16
17
// 4

18
$this.val(function() {
19
	return chunk.join("-").toUpperCase();
20
});

The main function, in this case:

  1. Gets the value from the input.
  2. Removes invalid characters, those being spaces, special characters like dots, underscores, and dashes.
  3. Splits the input into five chunks of characters. The first and the last chunk will each have eight characters. The rest (second, third, and fourth chunks) will consist of four characters each.
  4. Merges each piece with a dash, turns them into uppercase, and passes the value back to the input element.

Result

Our License Number input is now ready! Give it a go:

Bonus!

Check out this demo by Donnie D'Amato–an input for formatting dates:

Thanks Donnie!

Wrapping Up

In this tutorial, we walked through two examples of automatically formatting user input, giving our users a more seamless experience.

This approach is applicable for any type of text input. You could, for example, apply it to a “username” input to make sure that all letters are lowercase, and only contain letters. You could also use it to format a “First and Last Name” input, ensuring the first letter is capitalized.

When it comes to submitting the form and sanitzing the data properly, please get in touch with your friendly back-end developers.

Further Resources

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.