Setup JQuery Masked input in Rails 5


You have probably seen inputs that change the format of a text as you type. For example, a phone number, cell number or a date:

inputs that changes format

You can do it in Rails 5 using a nifty JQuery plugin called JQuery Masked Input.

The setup

Let’s start by installing the plugin through Yarn: yarn add jquery-mask-plugin

Your package.json will automatically be updated:

 {
   "dependencies": {
     "jquery-mask-plugin": "^1.14.12"
   }
 }

All of the plugins files will be generated in the node_modules folder.

Now you need to setup your app/assets/javascripts/applications.js:

//= require jquery-mask-plugin
//= require_tree .

$.jMaskGlobals.watchDataMask = true;

You can now use the jQuery Masked Plugin1 on any input by adding data-mask attribute on the input and the corresponding format as the value:

<%= f.text_field :number, class: 'form-control', 'data-mask': '000-000-0000', required: true %>

  1. For more information on how to use jQuery Masked Plugin, visit it’s homepage