I used masked-input-plugin, a simple jQuery plugin. My form contains something like:
<%= f.text_field :phone_number %>
(outputs [model_name]_phone_number)
and later
<%= f.text_field :postal_code %>
(outputs [model_name]_postal_code)
and this code applies the masks accordingly:
//Select anything with "phone" in it, and apply mask. '9's mean numbers only.
  $j('input[id*="phone"]').each (function(){
      $j(this).mask("(999) 999-9999");
    }
  );
  //Select anything with "postal_code" and apply mask
  //The '?' means anything following the '?' is optional.  In this case, the +4 on 
  //the postal code is optional.  Even though this is called postal code,
  //it's really only for a zip, since Canada (for instance) uses alphanumeric codes,
  //which will be disallowed in the input.
  $j('input[id*="postal_code"]').each (function(){
      $j(this).mask("99999?-9999");
    }
  );
  //Select anything with "max" (for instance my_max_users) and apply mask.
  $j('input[id*="max"]').each (function(){
      $j(this).mask("9?99999", {placeholder:""});
    }
  );
Any non-numeric input is ignored with the 9s, another sanity checking bonus. Now, as long as the user has javascript turned on, I can expect MOST of my input to be sanely formatted.
This was a very exciting find, and is really here in case I need to figure it out again in the future. Hopefully someone finds it who's trying to do the same thing -- that's why the title is so verbose.
~Nic

1 comment:
THANK YOU so much for this tip. I used for Grails project. It will save me a ton of time!
Post a Comment