Checking date formats in rails

My 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 am trying to verify that the date has the following format: mm / dd / yyyy. When I enter something that should be reliable, I still get an error message.

Thanks for the help. Here is a snippet of code from my form that passes the dob value to:

    <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 this may have something to do with my use of this js calendar plugin. A related problem is that my dob value is not supported in the field, if the message does not pass the validation - the previously entered date value is cleared ...

Thanks!

Tom

+3
source share
7

Rails-, . :

#!/usr/bin/ruby

str   = '08/24/2009'
regex = /\d{2}\/\d{2}\/\d{4}/

if str =~ regex
   print 'matched', "\n"
else
   print 'did not match', "\n"
end

. , .

Ruby, Date.parse method Date . , , .

+3

, . , , DateTime Time, . Rails, , , ( - 4 Rails DateTime Time).

: DateTime ( ), validates_format_of ( )

+6

gem/plugin .

validates_timeliness

http://github.com/adzap/validates_timeliness

+4

! , Rails , - , ( ).

/ , Rails , Date.Parse(http://www.ruby-doc.org/core/classes/Date.html#M000644),

u = Somemodel.find :first

u.created_at
=> Tue Nov 20 15:44:18 -0500 2007

u.created_at = '2008/07/03'
=> "2008/07/03"

u.created_at
=> Thu Jul 03 00:00:00 -0400 2008

u.created_at = '05/10/1980'
=> "05/10/1980"

u.created_at
=> Sat May 10 00:00:00 -0400 1980
+2

. http://www.rubyxp.com/, . , , , , rubyxp.

, - , da?

, : validates_timeliness, rails . , , . , 99/99/9999 , .

+1

, , :

def validate_date_format ()

current_date = DateTime.now
begin
  DateTime.strptime(current_date, value)
rescue
  raise 'Invalid Format'
end

+1

You can also look at the Chronic Gem ( http://chronic.rubyforge.org/ ), which performs natural date parsing. So you can enter:

Next Tuesday at 9 pm

And he will interpret it correctly.

0
source

Source: https://habr.com/ru/post/1715951/


All Articles