How to format dates and telephones in form_for?

Well, that’s basically it, how can I make an input field for date like mm/dd/yyyy and for telephone like +xx (xx) xxxx-xxxx.

Thank you,


make on javascript for that and call in :onkeypress => 'yourJS(this);' i think so

Can’t I do that only with ruby and rails?

Can't I do that only with ruby and rails?

make on javascript for that and call in :onkeypress => 'yourJS(this);' i think so

You could certainly clean up any user input in a before_validation filter method. I don't know how you would figure out which mask to use, but what I usually do is first strip out anything that isn't a numeral, and then take the numbers back through a mask so that first n numbers are area code, next are exchange, then station, then extension if anything is left over. If you had multiple nations or any optional elements (country code) then the problem gets a lot harder to solve.

By the way, as Leoncio pointed out, this could all be done in JavaScript, and the implementation is largely the same; string operations being more or less identical (and with Prototype.js, even having the same names for the functions) in either JavaScript or Ruby.


How can I manage to make it appear automatically, the + and () and - in the telephone +00(00)0000-0000 and the / in the date like mm/dd/yyyy, as the user types only numbers? And how to enable only numbers to be typed?

And what type are those kind of information saved in the database? strings?

That's done with JavaScript. Have a google for the term 'input mask', and step well back when you see the zillions of results.


Dude, one lil example:

put this in your public/javascript

function maskTelefone(source, event) {

return mask(source, event, '99 9999-9999', '0123456789');


then, in your view, call like this

<%= f.text_field :del_fone, :size => 13, :maxlength => 12, :onkeypress => “return maskTelefone(this,event);” %>

works fine fella!

any doubt, please, talk

Thank you, I didn’t quite understand cause I haven’t study javascript yet, but I think I got the idea.

Just one more thing, can I save all that just as strings in the database?

yep, no problem for that

I was talking to my group here and they said it’s more interesting to save telephone with numbers, is it ok if I save as integer and still appear the +, () and - automatically at the page?

Also what about the date and datetime types? How do I use them and is it better to use one of those instead of a string?

yep, much better keep just the numbers into database, better for search and cast (if necessary), dont save with "-"or “XX” and the other stuffs and occuped less space on DB

I would use Date, Datetime or Timestamp data types, depend on the problem you need to model, in order to model dates (and/or dates and times).

If you are already using jQuery you could use the jQuery UI datepicker ( You can configure the layout and many other options.

Hope it helps.