Input mask for phone form field in rails view

ctgScott picture ctgScott · Jul 27, 2013 · Viewed 9.2k times · Source

I have a customer contact form in my app which, of course, requires a phone input. I am running Rails 3.2.13 and using Zurb Foundation. I am hoping to find a gem that offers an input mask in the form '(999) 999-9999' that I can call. My data is really local so the US formatted numbers is all that I need.

I am able to perform the validation on the field but wanted to keep the users within the tighter boundaries of an input mask. This is what I have at the moment.

  <div class="large-4 columns"><%= f.telephone_field :phone, :placeholder => "Phone - (123) 456-7890" %></div>

Any great gems for this, or perhaps a jQuery plugin that you like?

Cheers!

-Edit So here is the full answer for what I needed to accomplish. Just in case anyone is looking for a quick fix. This is the code in my _form.html.erb view file:

<div class="large-2 columns">
   <%= f.text_field :phone, :id => "phone", :placeholder => "Primary Phone"%>
</div>

Here is the code in my coffee file in my assets/javascripts folder:

$ ->
   $("#phone").mask("(999) 999-9999")

You need to download the appropriate jquery.maskedinput.js file from the link @vinodadhikary mentions below. Then you must require the file somewhere below the jquery file in the list of dependencies in your application.js file like so:

//= require jquery
//= require jquery_ujs
//= require foundation
//= require jquery.maskedinput
//= require_tree .

That's about it. If you notice anything amiss, please let me know and I'll edit.

Answer

Tom Rossi picture Tom Rossi · Aug 22, 2015

I have been using the plugin http://digitalbush.com/projects/masked-input-plugin and it works pretty well.

I have a lot of fields with different masks so I use this method in my application coffescript.

  $( "[data-mask]").each (index, value) ->
    element = $(value)
    element.mask($(value).data('mask'))

Now I can just set a data-mask attribute on any of my fields::

      <%= f.text_field(:phone, data: { mask: '(999) 999-9999' }) %>

I hope this helps someone!