jQuery Masked Input Plugin

Today I want to discuss a jquery plugin that I have found to be useful.  It is the Masked Input Plugin.  It does three things: gives a visual representation to the client of the format of data we require, ensures they enter it that way, and does immediate validation.

Here is an example of a mask a user could see for phone input:
(___) ___-____

The mask is shown when the textbox receives focus. Underscores indictate where the user should type. Your mask restricts what you can type, and you cannot type anything beyond the mask.

Masks Rules:

When building your mask there are reserved characters with preset meanings:
  • a – Represents an alpha character (A-Z,a-z)
  • 9 – Represents a numeric character (0-9)
  • * – Represents an alphanumeric character (A-Z,a-z,0-9)
  • ? – Anything after a question mark is optional.
To create the phone mask portrayed above you would do this in script:
You can also create your own definitions.  In the examples below I have created some custom definitions to ensure specific characters are inputted in the correct positions (i.e., times must be prefixed with a 0 or 1.  No other numbers will work).  There is also a “completed” event which fires when all characters have been entered.  If your mask contains optional characters that are ignored then that function will not fire. In that case you may need to use the textbox’s blur event, or better yet, both events.

I have used these masks in past projects:

Standard Time Textbox:

This mask ensures users enter a Standard Time into the textbox (i.e., 03:30PM). For the period (AM/PM) it is case insensitive and will also accept the first character (A or P) or neither (in which case it will assume AM).  It will upcase the period.

Zip Code Textbox:

This mask ensures users enter a 5-digit Zip Code or Zip+4.  If anything is partially entered the textbox will clear.
Remember when these values are retrieved server-side they will be in the format shown in the textbox.

See a DEMO.

Enjoy.