I’ve had the chance to troll Donald Trump. But I didn’t.

The craziest thing that could possibly happen on my professional life as a Software Engineer happened on August 18th, 2016. That day I discovered that I could perform a massive Rick Roll attempt against the US presidential candidate Donald Trump.


The crazy story begins with an unexpected e-mail from a guy named Shu Uesugi – a San Francisco based Engineer currently working for EdSurge – asking for permission to mention my name and share to the world what he just discovered.

After reading his e-mail and his draft I was like:

The short story is that Donald Trump has a donate page which is using my open-source project jQuery Mask Plugin to guide his visitors on the tricky quest of filling up web forms – so far so good.

The shit hits the fan when the developer of his 2MM dollars website decides to include the minified version of jquery mask plugin file pointing directly to the demonstration page of my project (hosted in github.io). I have 100% control over this file and the developer simply injected the file on the page (instead of saving the file on his servers) and I could just replace or inject something nasty in it to make the most ambitious trolling attempt against the US presidential candidate.

Yet, in shock, I decided to share this with my personal friends on Facebook:

In only MY post I got 714 likes, 139 comments and an impressive 262 shares, hundreds of people randomly sending me friend requests, sending me messages on Twitter, Facebook and e-mails… giving me ideas and warning me about the window of opportunity that I got to do something about Trump. People really liked the possibilities of what Uesugi discovered . At the end of the post I asked for ideas of what each person would do if they were in my position – oh boy… that was fun!

All of the sudden I became some sort of super-man with a power that could change the world. People were like… DO IT! DO IT! Say something! Make a beautiful rain of penises with wings upon his website! And I was like… Wow… People really want to say something to this guy…

They even opened a hilarious pull request on their own, pure team work, in attempt to do something and hoping I’d merge it (sadly it was deleted).

The discovery was discussed everywhere:

After watching all this, receiving all those tweets, messages and emails showing nothing but pure hate love towards Trump. Of course, the bad news spreads fast and in a matter of hours the code on Trump’s website was fixed. People were in tears. e.g:

Screen Shot 2016-08-21 at 11.21.18 PM

Then I posted this on twitter:

Screen Shot 2016-08-21 at 11.18.18 PM

Yep. At the bottom of your heart you agree with me that this would be wrong. jQuery Mask Plugin is a serious project which took years of hard work and commitment to the community to build its reputation. I can’t just throw it all away for the public’s amusement. To make people laugh. To make a statement against someone – even if this someone is a US presidential candidate like Donald Trump.

Screen Shot 2016-08-21 at 11.22.27 PM

The true sad history behind this is that Donald Trump’s website cost 2MM dollars, they are using several open sourced projects like our jQuery Mask Plugin and they don’t even donated 1.00 freaking dollar in our donate page to support its development.

Posts Relacionados:

Deploying Sendy Using AWS ElasticBeanstalk and Docker

sendy-300x118In this post I’m going to guide you through a step-by-step on how to deploy your Sendy installation using AWS ElasticBeanstalk and Docker. Keep in mind that this is a production ready setup so brace yourself.

The AWS Resources

Here is a list of what you need to do before going ahead.

  1. Create an ElasticBeanstalk Application (e.g Sendy).
  2. Create an ElasticBeanstalk Environment (e.g sendy-production).
    1. You can deploy the Sample Application for now.
    2. Once your environment is created make a note of your Environment ID located on your environment dashboard right beside your DNS entry. (e.g Environment ID: e-xxxxxxxxxxx).
  3. Create a EC2 Security Group to be used by your RDS MySQL Instance (e.g: rds-sendy-production).
    1. Inbound: Open this tab and make sure you allowed your ElasticBeanstalk Instances can reach your RDS. To do so you need to locate the name of the Security Group created by your ElasticBeanstalk Environment. Just go to your EC2 Security Groups Section. And locate the ID of the security group that possessed your ElasticBeanstalk Environment ID.
    2. It will look kind of like this:
    3. You need to do that because your environment is elastic and every new created instance needs to inherit its permission to access the RDS instance.
  4. Create your RDS MySQL instance and attach the EC2 Security Group created on the previous step. Further configurations is up to you.
  5. Create a SSD or Magnetic Volume on the same Availability Zone of your Elastic Beanstalk Environment Instances. Attention to the availability zone or your deployment will fail because EC2 Instances can’t attach volumes outside of its availability zone. After doing that take a note on your Volume ID (e.g vol-XXXXXXXX).
  6. Install the awsebcli.

The Deploy Setup

Assuming that you’re already inside your Sendy’s folder you need to create a few files.


FROM php:7.0.8-apache

RUN a2enmod rewrite && \
    docker-php-ext-install mysqli gettext

ENV APP_HOME /var/www/html



Notice that I’m using the official php + apache2 docker image. I need to create my own Dockerfile because of Sendy’s dependencies like mysqli and gettext.


    environment: sendy-production
  application_name: sendy
  default_ec2_keyname: YOUR-EC2-KEYNAME
  default_platform: Docker 1.11.1
  default_region: us-east-1
  profile: null
  sc: null

This file is important when your are about to deploy your application to ElasticBeanstalk.


  "AWSEBDockerrunVersion": "1",
  "Ports": [
      "ContainerPort": "80"
  "Volumes": [
      "HostDirectory": "/uploads",
      "ContainerDirectory": "/var/www/html/uploads"
       "HostDirectory": "/session",
       "ContainerDirectory": "/var/www/html/session"
  "Logging": "/var/log/apache2/"

Ports: By default apache is running on port 80, no big deal here.
Volumes: The most important thing to notice on the code above is those “Volumes”. Sendy uses the the uploads/ directory to save everything you upload to its system so it’s very important for you to have those volumes mapped from the Docker Host into your containers to make sure that in case you need to restart your containers you don’t lose your persisted data (docker containers are stateless!).

The /session:/var/www/html/session is because it is where php is saving logged user sessions. Its better to save sessions outside of the application container. It make sure that every new deployment you don’t need to clean your cookies and login again (it sucks, I know!).


    command: "aws ec2 attach-volume --region us-east-1 --volume-id YOUR_VOLUME_ID_HERE --instance-id $(curl -s --device /dev/xvdf"
    ignoreErrors: true
    command: "sleep 20"
    command: "mkdir /uploads"
    test: "[ ! -d /uploads ]"
    command: mount /dev/xvdf /uploads
    ignoreErrors: true
    command: if find /uploads -maxdepth 0 -empty | read v; then mkfs -t ext4 /dev/xvdf; fi
    command: "mount /dev/xvdf /uploads"
    ignoreErrors: true
    command: "chmod -R 777 /session && chmod -R 777 /uploads"
    ignoreErrors: true

01mount: Replace the YOUR_VOLUME_ID_HERE by your Volume ID created before. Also make sure that –region us-east-1 is correct. This file will make sure that we will be using the Volume created earlier exclusive to our uploads and your data will never be lost in case you explode your machine somehow.
02wait: The commend aws ec2 attach-volume is async so we need this otherwise further commands would fail.
03mkdir: Create the /uploads dir in case it doesn’t exists.
04trymount and 05: When you first create a EC2 Volume you need to make sure that it has a file system in it so this is what it does.
06mount: Uses the Volume we created for the /uploads folder.


    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash
      set -x
      docker run -v /uploads:/var/www/html/uploads --rm aws_beanstalk/staging-app chown -R www-data: /var/www/html/uploads
    group: root
    owner: root
    mode: "000755"
    content: |-
      #! /usr/bin/python

      Modifies nginx configuration file on AWS Elastic Beanstalk to support WebSocket connections.

      import os
      import re

      NGINX_CONF_FILE = '/etc/nginx/sites-available/elasticbeanstalk-nginx-docker-proxy.conf'
      NGINX_CONFIG = """
      # nginx.conf
      # v1.0.4

      map $http_upgrade $connection_upgrade {
        default   "upgrade";
        ""      "";

      server {
        listen 80;

        gzip on;
        gzip_comp_level 4;
        gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
        client_max_body_size 100M;

        location ~ "^/assets/" {
          root /var/app/current/public;
          gzip_static on;
          expires max;
          add_header Cache-Control public;
          add_header ETag "";

        location / {
          proxy_pass      http://docker;
          proxy_http_version  1.1;

          proxy_set_header  Connection           $connection_upgrade;
          proxy_set_header  Upgrade              $http_upgrade;
          proxy_set_header  Host                 $host;
          proxy_set_header  X-Real-IP            $http_x_real_ip;
          proxy_set_header  X-Forwarded-For      $http_x_forwarded_for;

      def has_same_nginx_file_version():
        f = open(NGINX_CONF_FILE, "r")
        conf = f.read()
        ret = re.search(VERSION, conf)

        return ret != None

      def write_nginx_conf_file():
        f = open(NGINX_CONF_FILE, "w")

      def restart_nginx():
        print("-- service nginx restart")
        os.system("service nginx restart")

      def main():
        if has_same_nginx_file_version():
          print("-- already configured, do nothing.")
        else :

      if __name__ == "__main__":

The file above is necessary because apache runs your application with www-data user and this user doesn’t exists on your Docker Host. And the second file is for overwriting nginx’s beanstalk configuration for accepting upload of bigger files.


/* MySQL database connection credentials (please place values between the apostrophes) */
$dbHost = $_ENV['MYSQL_DATABASE_HOST']; //MySQL Hostname
$dbUser = $_ENV['MYSQL_DATABASE_USER']; //MySQL Username
$dbPass = $_ENV['MYSQL_DATABASE_PASSWORD']; //MySQL Password
$dbName = $_ENV['MYSQL_DATABASE_NAME']; //MySQL Database Name

Add these to your .htaccess file:

# for enabling upload of bigger CSV files
LimitRequestBody 104857600
php_value max_execution_time 0
php_value post_max_size 60M
php_value upload_max_filesize 50M

# to avoid session problems originally saved to /tmp.
php_value session.save_path '/var/www/html/session'

Make sure that you are using environment variables on that file so we can inject them into your ElasticBeanstalk Environment.

Set your database configuration as Environment Variables


Deploy it

Commit your changes and then:

eb deploy sendy-production

Boom! Now make sure that you follow Sendy’s Guide Lines in order to setup your app correctly.

Let me know if you have any questions on the comments section bellow. Maybe some detail is missing and I could add it to the post. Remember! Sharing is caring! ;-D

Posts Relacionados:

Farewell Brasil… Hello Portugal!

Hi. My name is Igor Escobar and I’m a Software Engineer at Hole19 Golf. As many of you already know, I recently made a life changing decision of which I would love to talk about with you.

Before going through the why’s, I need you to understand I little bit about me so you can follow my reasoning on why I did leave Brasil.

I started into programming when I was 13 years old. Loved it since the first time I laid eyes on those crazy computer instructions. Did all kinds of crazy computer programs you can imagine and I’ve learned that magical things only happen way out of your comfort zone.

This motto not only tells a lot about myself but also tells a lot about our mindset and the kind of challenges that we are able to pursue. I’ve always dreamed big, always pictured myself out there, living this dream of endless freaking awesome challenges.

A few months ago I stumbled on the opportunity of joining a Portugal based startup called Hole19 Golf. I can tell you that it wasn’t an easy decision.

Some of you would call me crazy for leaving Brasil (some of you definitely wouldn’t), but not everyone has the courage needed to put your entire life upside down… leaving your family, selling everything you once possessed, job, home (~/) and my wife (also a dog) for endless 4 months.

When this kind of opportunity appears in your life you can’t think just about yourself. You need to think about your family, your future, is it worth it? Does Portugal have better safety conditions, education? Will my kids have a better life there? For many of you It may sound like “it’s just a job, not worth it!” but in my head it sounded completely different.

I saw an entire new world opening before my eyes. Portugal in 2016 held the 13th position in terms of Quality of Life right after Finland and United States which holds the 12th position. Portugal has better qualify of life compared with amazing places like UK, Canada, Japan, France, Ireland, Italy and the list goes on! Where is Brasil on that list? 45th place… right next to India, Iran, Pakistan, Singapore etc.

As hard as it may be… For the sake of my future family of 3 kids and two dogs… I really believed that a huge shiny door was opening for me.

It’s been 5 months since I left Brasil and started a whole new life in Portugal as a Software Engineer at Hole19 Golf and I feel morally obligated to tell you about how my life’s going in Lisbon/Portugal and how it’s like to be working for Hole19.

Life in Lisbon/Portugal

Instead of going through all the aspects of living in Portugal I rather talk about a few things that most impressed me on a daily basis.


When I moved to Lisbon I discovered that I’m a guy who likes to walk around. Day and night. This is impossible in Brasil if you don’t live in a private condo with security cameras, high walls or electrified fences. Lisbon proved to be a very nice place to walk around and discover the city. It felt really safe and you can walk around anytime, day or night, and still get home safe with all pieces in place. Also, if you value living in a nice house close to the ocean or with green areas everywhere, Portugal fits you well and you don’t have to sell one of your kidneys for it or drive for a hundred hours to get to work.

Beauty and people

Lisbon is beautiful and it surprises me every time I go for a walk, day or night. The portuguese are known for being quite surly, but all I can say is that in Lisbon I was always well attended, so I didn’t feel any of that so called rudeness. Of course, you can relate that to the fact that Lisbon is a big city and full of tourists and that influences how portuguese treat visitors.

Pictures above were all taken by me. Most of those places you can visit by just walking around. These are just a few places that I’ve been for this very short period living here. It’s amazing(!).


If you think you’re coming to Lisbon and you’re not putting on some extra pounds, you’re wrong. The variety of restaurants here is impressive. And to make it better you eat very well and pay fair prices for it. I guarantee that eating well won’t be an issue for you. This made things easier for me, considering that brazilian food is really good and that my first four months I was living by myself.


For me, this is a huge positive point. Lisbon is cold in the winter but not FREAKING ICE AGE like in other countries and it’s very nice in the summer. The only thing you need to be aware is the pacific freaking cold ocean incluencing the Tejo River.

Public Transportation

In my opinion it works perfectly. We got buses, trams, funiculars, subway, trains and boats. I could go anywhere I wanted using them for very affordable rates.

And these were the aspects that impacted me the most in this time frame.

Life and Work at Hole19

Since the first moment I decided to join Hole19 they started to be like a family to me. They took care of every aspect of my moving to Portugal like documentation, plain tickets, costs, temporary place to stay, everything! They even picked me up at the airport, by the way.

And it’s been like a family ever since. We work and we work hard to connect the world of golf! Together we were able to accomplish amazing things! Even more that I could ever imagine. Our team is incredibly passionate and talented. We are so focused on our mission that you can’t even think about doing poor work – its like everybody is watching and this is amazing!

2016-01-28 16.41.47

It really feels like we are all part of a huge mission (it really has been). If you don’t like to work on a world class product used by 1M people, across 154 countries and 14 languages, to create highly performant applications, solve scale issues, work on recommendation/search algorithms, social connections with Graph databases, to process several thousands of requests per second, to deal with payments, (No)SQL/in memory databases, streaming data processing/transformation/aggregation, distributed architectures, math problems, to create technology for mobile/wearable devices, to use the right programming language to solve the problem, to use containers, continuous integration and deployment and to create APIs… this is definitely NOT the place for you.

It has been an exciting ride for me. I’ve always been a guy that thinks that with the right people, hard work and a huge load of passion you can accomplish anything. So I think we’re on the right track.

This post is also available on Medium.

Posts Relacionados:

  • Nenhum post relacionado!

Working with Asterisk and Node.js

Screen Shot 2014-08-13 at 2.21.49 PM Screen Shot 2014-08-13 at 2.22.23 PM I’ve been working on a very cool project project here at Vale Presente which was able to provide a smooth interface to our call center attendees increasing their productivity and quality of our costumer service. The project was built with HTML5, CSS3, Javascript and Node.js as our backend engine (only cool stuff!). But the main challenge was finding the right tool to get the job done in a fast and consistent manner. I’m not going to talk about how I built the client. My focus here is talk about the tool I used to create a fast and consistent connection between the attendees and Asterisk. That was tough. There are a lot of libraries available over the Internet but most of them aren’t production ready.

Production ready

During my quest I had the pleasure to meet asterisk-manager. A Asterisk Manager Interface created by Philipp Dunkel which is a node.js module for interacting with the Asterisk Manager API. Nowdays I’m helping him as a maintainer of the project, improving, fixing bugs and helping to increase the project’s visibility. Not just because I’m a maintainer but because it works!

Currently the asterisk-manager module/package for node.js is handling incredibly well more than 500,000 asterisk events and ~5,000 voice calls a day. All of those events are being transmitted to our clients through Socket.io. This is a production ready and tested solution.

How to use it

Pretty simple. First you have to install it directly:

npm install asterisk-manager

Or put it inside of your package.json:

 "dependencies": {
    "asterisk-manager": "0.1.x"

Now you have to create a connection instance with your asterisk server:

var AsteriskManager = require('asterisk-manager')
  , ami = new AsteriskManager(config.asterisk.port, config.asterisk.host, config.asterisk.user, config.asterisk.password, true)

And that’s it! It works! Now you have to take a closer look inside of the available events and actions and have fun!


The list of all available events which is supported by Asterisk Manager API can be found here: https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+AMI+Events How do I listen for any/all AMI events?

ami.on('managerevent', function(evt) {});

How do I listen for specific AMI events?

ami.on('hangup', function(evt) {});
ami.on('confbridgejoin', function(evt) {});

What if my connection dropped? You can listen to the connection events like:

ami.on('close', function(e) {});
ami.on('disconnect', function(e) {});
ami.on('connect', function(e) {});

And make your own decision on what do to next.


The list of all available actions supported by Asterisk Manager API can be found here: https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+AMI+Actions How do I call an action?

  'channel': "SIP/1234",
  'exten': '1143224321',
  'context': 'from-internal',
  'priority': '1'
}, function(err, res) {});

And that’s it! Have fun!

Github: https://github.com/pipobscure/NodeJS-AsteriskManager NPM Repository: https://www.npmjs.org/package/asterisk-manager Bug Reports: https://github.com/pipobscure/NodeJS-AsteriskManager/issues

Posts Relacionados:

  • Nenhum post relacionado!

Using jQuery Mask Plugin with Zepto.js

Running jQuery Mask Plugin with Zepto.jsToday I’m going to exemplify a pretty easy way to put jQuery Mask Plugin to run with Zepto.js instead of jQuery.

What is Zepto.js

Basically, you can switch from jQuery to Zepto.js if it’s too heavy or if it’s too much for your current needs. If you need something more lightweight that allows you to keep your code compatible with your old jQuery’s code, Zepto.js is a match for you.

Zepto is a minimalist JavaScript library for modern browsers with a largely jQuery-compatible APIIf you use jQuery, you already know how to use Zepto. While 100% jQuery coverage is not a design goal, the APIs provided match their jQuery counterparts. The goal is to have a ~5-10k modular library that downloads and executes fast with a familiar and versatile API, so you can concentrate on getting stuff done.
Zepto.js Official Web Site

How to

Recently, Igor Lima made a pretty cool contribution to jQuery Mask Plugin making a few tweaks on jQuery Mask Plugin’s code to make it run smoothly with Zepto.js, making things even easier for you.

Since version 0.9.0 all you have to do is:

1 – Load zepto.js between your head TAG (or where ever you want to put it if you know what you’re doing):

<script type="text/javascript" src="http://zeptojs.com/zepto.min.js"></script>

Load the Zepto.js data plugin right after Zepto.js:

<script type="text/javascript" src="https://raw.github.com/madrobby/zepto/master/src/data.js"></script>

Zepto’s basic implementation of data() only stores strings. To store arbitrary objects the optional “data” module from custom build of Zepto was included.

And then load jQuery Mask Plugin:

<script type="text/javascript" src="https://raw.github.com/igorescobar/jQuery-Mask-Plugin/master/jquery.mask.min.js"></script>

All you need to do now is take a look into jQuery Mask Plugin Documentation to learn a little about jQuery Mask Plugin’s API and you’re ready to go!

Did it help you? Support jQuery Mask Plugin!

Click here to lend your support to: jQuery Mask Plugin and make a donation at pledgie.com !

Posts Relacionados:

  • Nenhum post relacionado!

Adding and removing remote branches

Today I’m going to share another git’s trick to easily set up a remote branch and how to delete them from the remote branch.

Frequently we have to work parallelly to master branch on an exciting feature of your product, right? More often then this is sharing it so your co-workers can contribute and make it even more exciting.

Adding remote branches

The problem is that every time that you create a new branch it’s created locally and you can’t just push your changes because git doesn’t know where to push it. Git stores your branch’s configuration on your .git/config file like this:

[branch "ftw_feature"]
  remote =
  merge =

You can solve this problem manually, every goddamn time setting branch’s remote configurations in .git/config file or if you’re working with git’s version 1.7+ you can use the –set-upstream flag instead.

git branch --set-upstream ftw_feature origin/ftw_feature

Now, just like magic your .git/config file should look like this:

[branch "ftw_feature"]
  remote = origin
  merge = refs/heads/ftw_feature

Or if your you’re sadly running under 1.7 git’s version you can still do a better approach than manually (or not too verbose for me):

git config branch.ftw_feature.remote origin
git config branch.ftw_feature.merge refs/heads/ftw_feature

Removing remote branches

If somehow you screw things up and have to clean the mess before anyone notices, just type:

git push origin :ftw_feature

Or even more intuitive:

git push origin --delete ftw_feature

That does the job.

Posts Relacionados:

  • Nenhum post relacionado!

Making Sinatra routes insensitive to the trailing backslash

Today I’m going to talk about how we make Sinatra routes insensitive to the trailing backslash. This trick will help you if you just got started with Sinatra.

Now that you’re creating RESTful apps and decided that Sinatra it’s your chosen one framework, it’s very important that you always end your routes with a “/?”. It’s important not to forget that Sinatra accepts regular expressions on their routes. If you create a simple route like this:

get "/twitter-posts" do
  # some code
  haml :index, :format => :html5

Sinatra will not understand the route if typed like this: “/twitter-posts”. With that in mind, it’s very important that you always end up your routes like this:

get "/twitter-posts/?" do
  # some code
  haml :index, :format => :html5

Now, you’re telling Sinatra that your route has a optional trailing backslash and now will understand both with or without trailing backslash.

Posts Relacionados:

  • Nenhum post relacionado!

Mascara Javascript para os novos telefones de São Paulo

Olá pessoal,

“O presidente da Anatel (Agência Nacional de Telecomunicações), João Rezende, informou nesta sexta-feira que o acréscimo do nono dígito aos números de celulares da região metropolitana de São Paulo vai garantir 53 milhões de novas combinações numéricas.”

Sabendo disso, é importante começarmos a pensar em soluções para atender as mascaras de telefone de todo o Brasil e também para região metropolitana de São Paulo.

Já faz uns meses que falei sobre o  jQuery Mask Plugin. E desta vez, também vamos resolver este mesmo problema com o ele. Criei um exemplo no jsFiddle de como resolver da mascara javascript com o novo nono dígito nos telefones celulares de São Paulo. Você pode ver o exemplo funcionando aqui: http://jsfiddle.net/d29m6enx/2/

E o código é este:

// using jQuery Mask Plugin v1.7.5
// http://jsfiddle.net/d29m6enx/2/
var maskBehavior = function (val) {
 return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
options = {onKeyPress: function(val, e, field, options) {
 field.mask(maskBehavior.apply({}, arguments), options);

$('.phone').mask(maskBehavior, options);

Desta forma, atendemos todos os números de telefone do Brasil e também atendemos a nova forma da Anatel para os telefones da região metropolitana de São Paulo, simples, certo? Ainda bem que tive a ideia de implementar estes eventos nas mascaras antes mesmo desta norma da Anatel 🙂

É isso, simples e objetivo!

UPDATE 10/10/2014

Eu e o @dgmike fizemos uma versão um pouco mais otimizada da solução apresentada pelo Bruno Porto em comentário:

Ajudou? Ajude no desenvolvimento do jQuery Mask Plugin

Click here to lend your support to: jQuery Mask Plugin and make a donation at pledgie.com !

Posts Relacionados:

Masks With jQuery Mask Plugin

Today is the oficial release of the version 0.4.3 of my jQuery Mask Plugin. Since I have never written about it before on this blog, I’ll teach you guys how to use it and some other cool features about it.

Downloading the code

 wget https://github.com/igorescobar/jQuery-Mask-Plugin/blob/master/jquery.mask.min.js 

The only thing that you guys need to do is include the javascript file of the plugin between the head tag in your HTML document and it’s all set to use.

The syntax

The jQuery Mask Plugin syntax is pretty simple. First, you input your  selector, followed by the .mask and then as a parameters you have to put the mask that you want the plugin to apply on the form field.


In this example the mask 00/00/0000 will be applied in all the input fields that have the “.date” class. At jQuery Mask Plugin you don’t have pre-established masks, you choose the mask as you wish. On the website project you can see the jQuery Mask Plugin running with some others examples like this:

  $('.date_time').mask('00/00/0000 00:00:00');
  $('.phone_with_ddd').mask('(00) 0000-0000');
  $('.phone_us').mask('(000) 000-0000');
  $('.mixed').mask('AAA 000-S0S');
  $('.cpf').mask('000.000.000-00', {reverse: true});
  $('.money').mask(',00', {reverse: true});

As you can see, it’s possible to define other data type on each digit of the mask. This mask for example:

$('.mixed').mask('AAA 000-S0S');

The user can type a sequence of three alpha numeric characters, followed by space, three numeric characters, a slash, one string character, other number character and finally one string character, cool isn’t it?

Again, you can define the mask as you wish and the data type of each digit of the mask as well.


  • Lightweight (~2kb minified, ~1kb gziped).
  • Masks on any HTML element!
  • data-mask attribute support.
  • String/Numeric/Alpha/Mixed masks.
  • Reverse mask support for masks on numeric fields.
  • Sanitization.
  • Optional digits.
  • Digits by range.
  • Automatic maxlength.
  • Advanced mask initialization.
  • Callbacks.
  • On-the-fly mask change.
  • Mask removal.
  • Customization.
  • Compatibility with Zepto.js

More about jQuery Mask Plugin

  1. jQuery Mask Plugin on Github
  2. Demonstration
  3. jQuery Mask Plugin
  4. All versions of jQuery Mask Plugin

Any problems, please, let me know.

Help us!

Click here to lend your support to: jQuery Mask Plugin and make a donation at pledgie.com !

Posts Relacionados:

Mudando a barra de endereço do browser sem refresh

Hoje vamos falar sobre um recurso bastante interessante dos nossos browsers que nos permite fazer a alteração das informações das páginas que acessamos, inclusive a URL que é mostrada na barra de endereço do seu browser sem fazer o uso do refresh e o melhor: mantendo o histórico.

Manipulando o histórico do browser

Para se fazer o que é proposto neste post é preciso entender como funciona a manipulação do histórico do nosso browser e os métodos que o objeto DOM window nos proporciona para manipular o nosso histórico. Neste post vamos falar especificamente sobre o window.history.

W3C implementa History com a seguinte interface:

interface History {
  readonly attribute long length;
  readonly attribute any state;
  void go(optional long delta);
  void back();
  void forward();
  void pushState(any data, DOMString title, optional DOMString url);
  void replaceState(any data, DOMString title, optional DOMString url);

Neste post, vou falar somente somente os métodos pushState e replaceState que são os métodos responsáveis por manipular o histórico da sessão do seu navegador.

Sempre que você abre uma nova aba e/ou janela o navegador inicia uma nova sessão. E é nesta sessão que ele armazena todas as URL’s que você visitou.

Método history.pushState

O método pushState registra uma nova entrada no seu histórico de sessão, mantendo o histórico. E essa é a sua sintaxe:

window.history.pushState(data, title [, url ] )

Data: O parâmetro data pode ser útil caso você queira utilizar o evento onPopState. O evento onPopState é invocado sempre que uma nova entrada é registrada no seu histórico de sessão.
Title: É o título da página que você quer que esta entrada tenha.
URL: É a URL que você quer que a página tenha. Você pode utilizar este parametro de duas formas:

  1. Absoluta: Passando toda a nova URL completa, incluindo protocolo, host, path etc. Ex: http://blog.igorescobar.com/
  2. Relativa: A URL que você passar será relativa a URL atual, ou seja, se você estiver acessando o http://blog.igorescobar.com/ e passar “/category/javascript/” a URL que será registrada é “http://blog.igorescobar.com/category/javascript/”.


 window.history.pushState('Object', 'Categoria JavaScript', '/category/javascript/'); 

O resultado deste código vai fazer com que a URL e o título da página que você estiver navegando mude, sem que o refresh ocorra. E se você apertar o “voltar” no seu navegador, vai ver que ele vai voltar a página anterior que você tinha acessado, ou seja, o histórico foi mantido.

Método history.replaceState

O método replaceState é muito parecido com o pushState. A única diferença entre os dois métodos é que o pushState armazena uma nova entrada, mantendo o histórico. O replaceState não, ele substituí a entrada do histórico de sessão atual pelos dados que você passa. E essa é a sua sintaxe:

window.history.replaceState(data, title [, url ] )


window.history.replaceState('Object', 'Titulo da Página', '/outra-nova-url');

Evento onPopState

O evento onpopstate é invocado sempre que uma nova entrada é dada no histórico de sessão do seu browser. A forma como você pode utiliza-lo é só adaptar à sua necessidade de negócio. Uma forma de utilização deste evento é delegar para ele a responsabilidade de carregar via ajax todo o link que for clicado, por exemplo.

Exemplo de navegação sem refresh

Todo mundo já conhece o GitHub, certo? (espero que sim!) O GitHub faz do uso deste mesmo recurso para que vocês consigam visualizar os arquivos de um repositório de maneira rápida, sem refresh e mantendo um histórico da navegação. Veja que sempre que você clica em um arquivo, ele é carregado dentro do mesmo contexto, a url da página muda e você consegue ir para frente e voltar no histórico, graças ao método window.history.pushState.

Este é um exemplo de como seria a implementação de uma navegação parecida com jQuery.

$('#menu-nav a')​​.click(function(e){
  window.history.pushState({url: "" + $(this).attr('href') + ""}, $(this).attr('title') , $(this).attr('href'));

$(window).bind("popstate", function(e) {


Os browsers Chrome, Opera, Safari e Firefox 4+ implementam todos estes métodos de forma nativa. Os browsers antigos utilizam o location.hash para imitar o comportamento. Existe uma biblioteca chamada History.js que implementa esta funcionalidade de forma crossbrowser.


Posts Relacionados: