João Paulo Cercal

Staff Security Engineer at LastPass

jQuery Mask: Masks for form fields

  • Share on Facebook
  • Share on Twitter
  • Share on LinkedIn

Read this article in

A simple and quick way to add masks to form fields is to use a jQuery plugin, this plugin is called Masked Input Plugin.

To create a mask, you just need to provide a simple javascript command, with only the following rules:

  • a – Represents an alphabetic character (A-Z, a-z)
  • 9 – Represents a numeric character (0-9)
  • * – Represents an alphanumeric character (A-Z, a-z ,0-9)

Let’s look at some practical examples:

Note: we’re using the jQuery selector through the ID attribute.

Mask for a Telephone field:

1
2
3
// <input type="text" id="telefone" name="telefone">

jQuery("#telefone").mask("(99) 9999-9999");

Mask for an RG field:

1
2
3
// <input type="text" id="rg" name="rg">

jQuery("#rg").mask("9.999.999");

Mask for a CPF field:

1
2
3
// <input type="text" id="cpf" name="cpf">

jQuery("#cpf").mask("999.999.999-99");

Mask for a Date field:

1
2
3
// <input type="text" id="data" name="data">

jQuery("#data").mask("99/99/9999");

Mask for a Time field:

1
2
3
// <input type="text" id="hora" name="hora">

jQuery("#hora").mask("99:99");

Mask for a Postal code field:

1
2
3
// <input type="text" id="cep" name="cep">

jQuery("#cep").mask("99999-999");