I have a form where my users can register to my site.
They fill in theirs birthdate in the form: birthyear, birthmonth and birthday.
So I am using Range to create the select in the form like this:
= f.select(:birthmonth, options_for_select((1..12)))
But that doesn't start the single digit numbers with a zero like i want: 01, 02, 03, 04, 05, 06, 07, 08, 09, 10 and so on..
I have even tried this but it didn't work:
= f.select(:birthmonth, options_for_select((01..12)))
Anybody that know how to get Range to start with leading zeros? Or any other way to do this so I can use it in the validation?:
validates_inclusion_of :birthmonth, :in => 1..12
You can actually just do: '01'..'12'
The trouble is that numbers themselves don't have leading zeroes (or, alternately, have an infinite number of leading zeroes that are never printed). To get leading zeroes, you need strings. Fortunately, Ruby comes with this sort of string formatting ability built in.
= f.select(:birthmonth, options_for_select((1..12).map {|n| "%02d" % n}))
The %02d
is a formatting specifier that means "pad it with leading zeroes if it's less than two digits."
For validation, you'll need to do the same conversion:
validates_inclusion_of :birthmonth, :in => (1..12).map {|n| "%02d" % n}
(Thanks to @r-dub for pointing out that bit.)
If it is just a presentational issue, you can construct [text, value] pairs and pass them to options_for_select:
Given a container where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and the "firsts" as option text.
So, something like:
options_for_select((1..12).map {|n| ["%02d" % n, n]})
That way you should be able to keep your validation logic as is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With