How to Mask Input with jQuery?

Posted in jQuery

Masked Input With jQuery

Sometimes you need user to input data in a particular format like a credit card number or Social Security Number or a standard US phone number. By masking input of a particular textbox, you can change its behavior so that it accepts input only according to specified format, e.g. an input masked credit card number input box will only allow 16 digits of credit card number to pass through and won’t accept any other input.

Here’s how to do just that with jQuery.

Grab the Masked Input Plugin by digitalBush and add a reference to it in head section of your page.

Now let us say you want to mask an input textbox so that it accepts only Tax ID numbers in the format 99-9999999. Firstly add a text input box to your page with say id as ‘taxid’. Now to mask the input for taxid, add this line to your jquery document ready function.

$('#date').mask("99-9999999");

In the above code, we passed a parameter to mask function to mask the input. Here 9 stands for an integer between 0-9. You can use a to denote alphabet(A-Z, a-z) and * to denote alphabets and numerals(A-Z, a-z, 0-9).

And if you need to define your own set of input symbols, you can define that too. Let us say you want to define a mask with character # that will let user input any number from 1-4. Add the following definition in the jquery ready function before you use this mask.

$.mask.definitions['#']='[1234]';

By default the mask function uses underscore to denote input points in text box. If you want to customize it to say dash ‘-‘ for a particular text box, you can pass an optional parameter to mask function.

$('#date').mask("99/99/9999",{placeholder:"-"});

With this masked input plugin, you can make your form inputs more user friendly and less error prone as it won’t allow any other input except those defined by the mask.

Tags:

Share


Subscribe to Full RSS Feed

RSS FeedIf you found this article useful, then consider subscribing to our RSS Feed or e-mail updates to stay updated with latest Web Design/ Development articles. You can also follow @webdevplus on twitter for latest updates.

One Response (Add Your Comment)

Comments are closed for this post.