5

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.

ctgScott
  • 231
  • 3
  • 6
  • 18
  • 4
    Have a look at: http://digitalbush.com/projects/masked-input-plugin/. Very nice plugin, check out the demo tab. – vee Jul 27 '13 at 05:53
  • Much appreciated! Looks perfect. – ctgScott Jul 27 '13 at 23:16
  • where do you add the `jquery.maskedinput.js` file? And I put the `.mask` function in the `x.coffee` where x is the controller where my form is. Is that correct? Thank you – Théo Capdet Aug 20 '15 at 15:09

1 Answers1

1

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!

Tom Rossi
  • 11,604
  • 5
  • 65
  • 96