Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating date formats in rails

My simple date validation regex is not working correctly...

validates_format_of :dob, :with => /\d{2}\/\d{2}\/\d{4}/, :message => "^Date must be in the following format: mm/dd/yyyy"

What am I missing here? I'm trying to validate that a date is in the following format: mm/dd/yyyy - When I enter what should be valid data, I still get the error message.

Thanks for the help so far. Here's a snippet of code from my form that is passing the dob value in:

    <tr>        
      <td>
        <%= f.label :dob, "Date of Birth:  " %>
      </td>
      <td>
        <%= calendar_date_select_tag "user[dob]", "", :format => :american, :year_range => 50.years.ago..0.years.ago %>
      </td>
    </tr>

I think it may have something to do with my use of this js calendar plugin. A related problem is that my dob value is not maintained in the field if the post fails validation - the previously entered date value clears out...

Thanks!

Tom

like image 833
cakeforcerberus Avatar asked Dec 01 '22 07:12

cakeforcerberus


2 Answers

You are probably using a string field to store a date. Consequently, any helpers that expect a DateTime or Time value will not work properly. You will need to investigate multiparameter assignments in Rails to figure out the proper way to do what you want to do (multiparemeter assignments is the magic behind sending 4 fields to Rails and get them converted to a DateTime or Time object).

In other words: if you are using a true DateTime field (as you should for this case) the validates_format_of will not have any effect (or will have adverse effects)

like image 57
Julik Avatar answered Dec 04 '22 04:12

Julik


Found an excellent gem / plugin for all your date / time validations.

validates_timeliness

http://github.com/adzap/validates_timeliness

like image 20
Dom Avatar answered Dec 04 '22 04:12

Dom