Format HTML input fields with JavaScript
This a quick example of how you can format HTML input fields with JavaScript to allow Credit Card numbers or let’s say Phone numbers in a particular format. Most often or not you might have seen this when you are trying to do a payment checkout. This article will cover the technique to format an HTML input field to your needs. I will be using plain vanilla JavaScript for my example.
Demo
Lets have a quick look at the demo gif, before we go over through the code.
What all is possible?
You can use it for
- Credit Card format (xxxx-xxxx-xxxx-xxxx)
- Date format (DD/MM/YYYY)
- Phone numbers (xx-xxxx-xxxxx)
- CVV (xxx)
Lots of possibilities. You can customize it to your needs, once you understand the technique
Code
Let’s jump onto the code. I will put up the HTML, JS, CSS source separately. Then I will explain each one of them. Let’s go,
HTML
<label for="creditcard">Enter Phone Number:</label>
<input placeholder="xx-xxxx-xxxx" type="text" id="phoneno"/>
<span class="comment">Example: xx-xxxx-xxxx</span>
<p class="comment">Only numbers allowed</p>
Pretty simple. That’s the HTML that will go in the body.
CSS
body {
font-family: sans-serif;
}
#phoneno {
width: 200px;
height: 25px;
font-size: 20px;
padding: 2px 10px;
}
.comment {
color: #9a9a9a;
font-size: 12px;
margin-left: 10px;
}
Again, very simple. Some basic styling added to the input field. I will not go into the details.
JavaScript
As you can see, I am using plain vanilla JavaScript. So this is very lightweight. You can port this to your React, Angular or VueJS application.
const phoneNoRef = document.querySelector('#phoneno');
phoneNoRef.addEventListener('keypress', (evt) => {
const code = evt.keyCode;
const val = evt.currentTarget.value;
const len = val.length;
//allow only numbers and backspace.
//hyphen will be added automatically
//user cannot enter hyphen
if(!((code >= 48 && code <= 57) || code === 8)) {
evt.preventDefault();
}
if(len === 2 || len === 7) {
console.log('add a hyphen');
evt.currentTarget.value += '-'
}
if(len === 12) {
console.log('do not allow any more');
evt.preventDefault();
}
});
Let me take you through the JavaScript source code.
Alright, so first I get a reference to the input field. Then add a keypress event listener. keypress is a standard DOM event available to us. However, our example will not work if you use keyup and keydown event. Can you guess why?
Then, I try to read the keyCode of the keyboard key pressed. I allow only numbers and backspace to remove the values once they are typed into the field. ASCII key codes for number 0-9 start from 48 and goes till 57. The keycode for backspace is 8. Pls note, that I am trying this on a Mac machine, key code might be different for the delete key on a Windows machine. So adjust your code accordingly.
Number | ASCII Key Code |
0 | 48 |
9 | 57 |
So, the first “if” condition restricts any character other than numbers.Users will not be able to type letters or special characters such as #, *, etc.
The second “if” condition keeps checking the length of the input value typed till now. Length starts from 0 since we are using the keypress event. So when the length is 2 that means we have typed 2 characters already and going to type the 3rd one, insert a hyphen (-) into the field. Since this is the demand of our phone number format. By now we have increased our length by a factor of 1 since we added the hyphen(-). Similarly, when the length is 7 we again insert a hyphen (-) to satisfy our format of xx-xxxx-xxxx.
The last “if” condition checks if we reached the end of our format and does not allow any more characters to be typed into the field.
And of course you can optimize and customize the code to your needs.
Try it out
Alright, here’s the live CodeSandbox link. Go ahead, give it a try.https://web.archive.org/web/20210613043547if_/https://codesandbox.io/embed/mask-input-field-xx-xxxx-xxxx-49vxf?fontsize=14&hidenavigation=1&theme=dark
Link: https://codesandbox.io/s/mask-input-field-xx-xxxx-xxxx-49vxf
I hope this small little example is helpful. Give me a shoutout in the comments section below if you have any issues using it. Cheers!