• Register now to get access to thousands of Tutorials, Leaked content, Hot NSFW and much more. Join us as we build and grow the community.

Advertise Here

Advertise Here

Advertise Here

Creating a Simple Input Masking using JavaScript Tutorial

wicked112

Sales Engagement Architect
W Rep
0
0
0
Rep
0
W Vouches
0
0
0
Vouches
0
Posts
104
Likes
19
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 2 900 XP
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. <head

    >
  4. <meta

    charset

    =

    "UTF-8"

    >
  5. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  6. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  7. <title

    >

    JS - Input Masking</

    title

    >
  8. <link

    rel

    =

    "preconnect"

    href

    =

    "https://fonts.googleapis.com"

    >
  9. <link

    rel

    =

    "preconnect"

    href

    =

    "https://fonts.gstatic.com"

    crossorigin>
  10. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0"

    /

    >
  11. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"

    >
  12. <link

    rel

    =

    "stylesheet"

    href

    =

    "style.css"

    >
  13. <script

    src

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"

    ></

    script

    >
  14. </

    head

    >
  15. <body

    >
  16. <div

    class

    =

    "content-md-lg py-3"

    >
  17. <div

    class

    =

    "page-title"

    >

    Creating a Input Masking using JavaScript</

    div

    >
  18. <hr

    style

    =

    "margin:auto; width:25px"

    class

    =

    "border-light opacity-100"

    >
  19. <div

    class

    =

    "container-lg"

    >
  20. <div

    class

    =

    "row py-3"

    >
  21. <div

    class

    =

    "col-lg-5 col-md-5 col-sm-10 col-12 mx-auto"

    >
  22. <div

    class

    =

    "card bg-dark rounded-0 border-dark-subtle"

    >
  23. <div

    class

    =

    "card-body rounded-0"

    >
  24. <!-- Sample Form -->
  25. <form

    action

    =

    ""

    >
  26. <div

    class

    =

    "container-fluid"

    >
  27. <div

    class

    =

    "mb-3"

    >
  28. <label

    for

    =

    "phone"

    class

    =

    "form-label text-light"

    >

    Phone</

    label

    >
  29. <input

    type

    =

    "text"

    id

    =

    "phone"

    name

    =

    "phone"

    class

    =

    "form-control form-control-sm phone-masking"

    required>
  30. </

    div

    >
  31. <div

    class

    =

    "mb-3"

    >
  32. <label

    for

    =

    "mobile"

    class

    =

    "form-label text-light"

    >

    Mobile</

    label

    >
  33. <input

    type

    =

    "text"

    id

    =

    "mobile"

    name

    =

    "mobile"

    class

    =

    "form-control form-control-sm mobile-masking"

    required>
  34. </

    div

    >
  35. <div

    class

    =

    "mb-3"

    >
  36. <div

    class

    =

    "mx-auto col-lg-4 col-md-6 col-sm-12 col-12"

    >
  37. <button

    class

    =

    "btn btn-dark border-dark-subtle rounded-pill w-100"

    >

    Submit</

    button

    >
  38. </

    div

    >
  39. </

    div

    >
  40. </

    div

    >
  41. </

    form

    >
  42. <!-- Sample Form -->
  43. </

    div

    >
  44. </

    div

    >
  45. </

    div

    >
  46. </

    div

    >
  47. </

    div

    >
  48. </

    div

    >
  49. <script

    src

    =

    "script.js"

    ></

    script

    >
  50. </

    body

    >
  51. </

    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. }


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. * @param {DOM Element} el
  9. * @param {Input Value Format [X = character]} format
  10. */
  11. constructor(

    el,

    format)

    {
  12. //set element
  13. this

    .el

    =

    el
  14. //Pattern Default Value
  15. this

    .pattern

    =

    [

    ]

    ;
  16. //Alternative Format Default Value
  17. this

    ._alt =

    [

    ]

    ;
  18. // Set Given Format
  19. this

    .format

    =

    String

    (

    format)

  20. //Match All X or (character groups)
  21. var

    FormatMatches =

    this

    .format

    .match

    (

    /(X+)/gi

    )
  22. var

    _altFormat =

    this

    .format

    ;

  23. //Default Input Pattern RegExp Value
  24. var

    inputFormat =

    '^'

    +

    this

    .format

    .replace

    (

    /

    [

    !@

    #$%^&*

    (

    )

    +=

    \[

    \]

    \\';,./{}|":<>?~]/g, "(\\

    $&)").replace(/\s

    /, "\\

    s")


  25. FormatMatches.forEach((pat, i) =>{
  26. //Set Matched Group with the pattern
  27. this.pattern[i+1]= `(\\

    d{${pat.length}})`
  28. //Replace Character Group to a Replacement Pattern
  29. _altFormat= _altFormat.replace(pat, `\$

    ${i+1}`);
  30. //Replace Character Group to RegExp Pattern as Input Patter Attribue
  31. inputFormat = inputFormat.replace(pat, `(\\

    d{${pat.length}})`);
  32. })
  33. // Join Pattern Array
  34. this.pattern = new RegExp(this.pattern.join('

    '))
  35. // Set Input Placeholder
  36. this.el.placeholder = this.format
  37. //Set Replacement Format to class object
  38. this._alt = _altFormat
  39. //Set input pattern
  40. this.el.pattern = inputFormat
  41. // Creating Sub text for input Format
  42. var inpFmtsub = document.createElement('

    div')
  43. inpFmtsub.innerHTML = `<span class="text-white-50 h6"><small>(${this.format})</small></span>`
  44. //Insert sub text after the input
  45. this.el.after(inpFmtsub)
  46. //Disable input'

    s autocomplete
  47. this

    .el

    .setAttribute

    (

    'autocomplete'

    ,

    'off'

    )

  48. //Trigger Input Masking / Format Value
  49. this

    .el

    .addEventListener

    (

    'input'

    ,

    this

    .mask

    .bind

    (

    this

    )

    )
  50. //Check if the current input value is equal to the complere require pattern/format
  51. this

    .el

    .addEventListener

    (

    'keydown'

    ,

    e =>

    {

    this

    .checkVal

    (

    e,

    this

    )

    }

    )
  52. }
  53. mask(

    )

    {
  54. //Re-format input value according to the given pattern
  55. this

    .el

    .value

    =

    String

    (

    this

    .el

    .value

    )

    .replace

    (

    this

    .pattern

    ,

    this

    ._alt)

    ;
  56. }
  57. checkVal(

    e,

    _this)

    {
  58. if

    (

    e.key

    .length

    ==

    1

    &&

    _this.el

    .value

    .length

    >=

    _this.format

    .length

    )

    {
  59. //Stop adding new character if the input already meet the required pattern
  60. e.preventDefault

    (

    )
  61. return

    false
  62. }
  63. }
  64. }

  65. window.inputMask

    =

    function

    (

    el,

    format)

    {
  66. //Initialize InputMasking Class to the given Element
  67. new

    InputMasking(

    el,

    format)
  68. }

  69. window.addEventListener

    (

    'load'

    ,

    (

    )

    =>

    {
  70. //Add Input Masking with format to a spedific input
  71. inputMask(

    document.getElementById

    (

    'phone'

    )

    ,

    '(XXX) XXX-XXXX'

    )
  72. inputMask(

    document.getElementById

    (

    'mobile'

    )

    ,

    '+XX XXX XXX XXXX'

    )
  73. }

    )


Snapshots

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

Form Panel

Filled with Correct Value

Filled with Incorrect Value

Filled

>
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 =)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

Create an account or login to comment

You must be a member in order to leave a comment

Create account

Create an account on our community. It's easy!

Log in

Already have an account? Log in here.

452,499

350,054

350,064

Top