Creating Masked Input Fields - J Query

There are certain input types that are quite error prone, like a credit card number. A simple typo that goes unnoticed at first can cause weird errors much later. That also applies to dates or phone numbers. These have a few features in common:

  • A fixed length

  • Mostly numbers

  • Delimiting characters at certain positions


A jQuery plugin that can improve the feedback is the masked input plugin. It is applied to one or more inputs to restrict what can be entered while inserting delimiters automatically.
In this example, a phone input is masked:

The plugin file is included in addition to jQuery itself. In the document-ready callback,the input with ID phone is selected, and the mask method is called. The only argument specifies the mask to use, here describing the format of a U.S. phone number.


There are four characters with a special meaning available when specifying the mask:


Any alpha character from a−z and A−Z


Any digit from 0–9


Any alphanumeric character, that is, a–z, A–Z, and 0–9


Anything after this is optional

Any other character, like the parentheses or hyphen in the phone mask, are considered literals, which the plugin automatically inserts into the input and which the user can’t remove.
By default, the plugin inserts an underscore ( _ ) for each variable character. For the phone example, the input would display the following value once focused:
(___) ___-____
When the user starts typing, the first underscore gets replaced if it is a valid character, here a digit. The other literals are skipped as well.
The underscore placeholder can be customized by passing an additional argument:

In this case, white space would be displayed instead of the underscore. It’s also possible to define new mask characters:

Here the new mask character is a tilde, and allowed values for it are + and −, specified as a regular expression character class. The tilde can then be used in a mask.
The quotation mark enables masks with a fixed part and an optional part. A phone number with an optional extension could be defined like this:

When a masked input is combined with the validation plugin, it’s important the field proper rules are defined for it. Otherwise, the validation plugin may accept the placeholder characters of the mask plugin as valid input, irritating the user when an invalid field is marked as valid while he just inserted the first character.


The significant limitation of the plugin is the fixed-length requirement. It can’t be used for anything with a variable length, like currency value. For example, “$ 999,999.99” would require a value between 100,000.00 and 999,999.99 and can’t accept anything above or below.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics