Creating a Simple Input Masking using JavaScript Tutorial

In this tutorial, you can learn how to create a simple Input Masking for formatting the HTML input values using only JavaScript. The tutorial aims to provide students and beginners with a reference for learning to create a useful component using JavaScript. Here, I will be providing a simple web page script that demonstrates the creation of a simple form with the masked input field.

What is Input Masking?

An input mask is a string expression that limits user input and is referred to in computer programming. It might be argued that it serves as a template, or predetermined format, to which all data must adhere in order to ensure data integrity and eliminate transcription errors. Although the syntax of this string expression varies depending on the implementation, all of the basic input types are accepted.

How can we create an Input Mask using JavaScript?

Input Mask can be achieved using some useful built-in methods, event listeners, and web APIs of JavaScript. Although there are now lots of free input masking JS plugins that are available on the internet, you might still want to learn how to create a custom one which means you are in the right place. We can create input masking with the use of Regular Expressions. Check out the web page scripts that I created and provided below to understand more about how to achieve this kind of component.

Sample Web Page Script

The script results in a simple web page that contains a simple form with phone and mobile number input fields. Each of the inputs has its own format or required template before the user can continue to submit the form.

Page Interface

Here is the HTML file script named index.html. It contains the page elements and the form inputs.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>JS - Input Masking</title>
  7. <link rel="preconnect" href="https://fonts.googleapis.com">
  8. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9. <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
  10. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  11. <link rel="stylesheet" href="style.css">
  12. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  13. </head>
  14. <div class="content-md-lg py-3">
  15. <div class="page-title">Creating a Input Masking using JavaScript</div>
  16. <hr style="margin:auto; width:25px" class="border-light opacity-100">
  17. <div class="container-lg">
  18. <div class="row py-3">
  19. <div class="col-lg-5 col-md-5 col-sm-10 col-12 mx-auto">
  20. <div class="card bg-dark rounded-0 border-dark-subtle">
  21. <div class="card-body rounded-0">
  22. <!-- Sample Form -->
  23. <form action="">
  24. <div class="container-fluid">
  25. <div class="mb-3">
  26. <label for="phone" class="form-label text-light">Phone</label>
  27. <input type="text" id="phone" name="phone" class="form-control form-control-sm phone-masking" required>
  28. </div>
  29. <div class="mb-3">
  30. <label for="mobile" class="form-label text-light">Mobile</label>
  31. <input type="text" id="mobile" name="mobile" class="form-control form-control-sm mobile-masking" required>
  32. </div>
  33. <div class="mb-3">
  34. <div class="mx-auto col-lg-4 col-md-6 col-sm-12 col-12">
  35. <button class="btn btn-dark border-dark-subtle rounded-pill w-100">Submit</button>
  36. </div>
  37. </div>
  38. </div>
  39. </form>
  40. <!-- Sample Form -->
  41. </div>
  42. </div>
  43. </div>
  44. </div>
  45. </div>
  46. </div>
  47. <script src="script.js"></script>
  48. </body>
  49. </html>

Custom Stylesheet

Here is the custom CSS file script of the web page. It contains some of the custom designs of the web page elements. The file is known as style.css.

  1. @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@200&family=Space+Mono&display=swap" rel="stylesheet');
  2. :root{
  3. --space-mono-font: 'Space Mono', monospace;
  4. --border-dark-subtle: #373838;
  5. }
  6. *{
  7. box-sizing: border-box;
  8. }
  9. body *{
  10. font-family: var(--space-mono-font);
  11. }
  12. /**
  13. Page Design
  14. */
  15. body,
  16. html{
  17. height: 100%;
  18. width: 100%;
  19. margin: 0;
  20. padding: 0;
  21. }
  22. body{
  23. background-color: #282A3A;
  24. }
  25. .page-title{
  26. font-size: 2.5rem;
  27. font-weight: 500;
  28. color: #fff;
  29. letter-spacing: 3px;
  30. font-family: var(--secular-font);
  31. text-align: center;
  32. text-shadow: 0px 0px 3px #2020208c;
  33. }
  34. .border-dark-subtle{
  35. border-color: var(--border-dark-subtle) !important;
  36. }
  37.  

Main Script

Lastly, here is the JavaScript file script known as script.js. It contains the custom Input Masking class. The class contains the codes that initialize the input element into masked input and update the input value to a given format or template.

  1. class InputMasking{
  2. el;
  3. format;
  4. pattern;
  5. _alt;
  6.  
  7. /**
  8.   *
  9.   * @param {DOM Element} el
  10.   * @param {Input Value Format [X = character]} format
  11.   */
  12. constructor(el, format){
  13. //set element
  14. this.el = el
  15. //Pattern Default Value
  16. this.pattern = [];
  17. //Alternative Format Default Value
  18. this._alt = [];
  19. // Set Given Format
  20. this.format = String(format)
  21.  
  22. //Match All X or (character groups)
  23. var FormatMatches = this.format.match(/(X+)/gi)
  24. var _altFormat = this.format;
  25.  
  26. //Default Input Pattern RegExp Value
  27. var inputFormat = '^' + this.format.replace(/[!@#$%^&*()+=\[\]\\';,./{}|":<>?~]/g, "(\\$&)").replace(/\s/, "\\s")
  28.  
  29.  
  30. FormatMatches.forEach((pat, i) =>{
  31. //Set Matched Group with the pattern
  32. this.pattern[i+1]= `(\\d{${pat.length}})`
  33. //Replace Character Group to a Replacement Pattern
  34. _altFormat= _altFormat.replace(pat, `\$${i+1}`);
  35. //Replace Character Group to RegExp Pattern as Input Patter Attribue
  36. inputFormat = inputFormat.replace(pat, `(\\d{${pat.length}})`);
  37. })
  38. // Join Pattern Array
  39. this.pattern = new RegExp(this.pattern.join(''))
  40. // Set Input Placeholder
  41. this.el.placeholder = this.format
  42. //Set Replacement Format to class object
  43. this._alt = _altFormat
  44. //Set input pattern
  45. this.el.pattern = inputFormat
  46. // Creating Sub text for input Format
  47. var inpFmtsub = document.createElement('div')
  48. inpFmtsub.innerHTML = `<span class="text-white-50 h6"><small>(${this.format})</small></span>`
  49. //Insert sub text after the input
  50. this.el.after(inpFmtsub)
  51. //Disable input's autocomplete
  52. this.el.setAttribute('autocomplete', 'off')
  53.  
  54. //Trigger Input Masking / Format Value
  55. this.el.addEventListener('input', this.mask.bind(this))
  56. //Check if the current input value is equal to the complere require pattern/format
  57. this.el.addEventListener('keydown', e => {this.checkVal(e,this)})
  58. }
  59. mask(){
  60. //Re-format input value according to the given pattern
  61. this.el.value = String(this.el.value).replace(this.pattern, this._alt);
  62. }
  63. checkVal(e, _this){
  64. if( e.key.length == 1 && _this.el.value.length >= _this.format.length){
  65. //Stop adding new character if the input already meet the required pattern
  66. e.preventDefault()
  67. return false
  68. }
  69. }
  70. }
  71.  
  72. window.inputMask = function(el, format){
  73. //Initialize InputMasking Class to the given Element
  74. new InputMasking(el,format)
  75. }
  76.  
  77. window.addEventListener('load', ()=>{
  78. //Add Input Masking with format to a spedific input
  79. inputMask(document.getElementById('phone'), '(XXX) XXX-XXXX')
  80. inputMask(document.getElementById('mobile'), '+XX XXX XXX XXXX')
  81. })
  82.  

Snapshots

Here are the snpashots of the overall result of the web page scripts I provided above.

Form Panel

Input Masking using JavaScript

Filled with Correct Value

Input Masking using JavaScript

Filled with Incorrect Value

Input Masking using JavaScript

Filled

Input Masking using JavaScript

>

DEMO VIDEO

There you go! I have also provided the source code zip file of all the complete scripts that I provided above. The zip file is available on this website. The download button is located below this tutorial's content.

That's it! I hope this Creating a Simple Input Masking using JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment