0

I've read this question and changed my rails model code accordingly: Regular expressions with validations in RoR 4

Here's my regex for my datetime in rails:

/\A((19[7-9][0-9])|(2[0-9][0-9][0-9]))\/((0[1-9])|(1[0-2]))\/(([0-2][0-9])|(3[0-1]))\s(([0-1][0-9])|(2[0-4]))\:([0-5][0-9])\z/

This regex below works in javascript, though:

/^((19[7-9][0-9])|(2[0-9][0-9][0-9]))\/((0[1-9])|(1[0-2]))\/(([0-2][0-9])|(3[0-1]))\s(([0-1][0-9])|(2[0-4]))\:([0-5][0-9])$/

I'm trying to pass a datetime string to them both, but I can't understand why it keeps failing. Here's the string:

2014/12/02 11:06

I thought my model code might be helpful:

validates :start, presence: true, format: { :with => /\A((19[7-9][0-9])|(2[0-9][0-9][0-9]))\/((0[1-9])|(1[0-2]))\/(([0-2][0-9])|(3[0-1]))\s(([0-1][0-9])|(2[0-4]))\:([0-5][0-9])\Z/, :message => "must be in this format: YYYY/MM/DD HH:MM" }
validates :finish, presence: true, format: { :with => /\A((19[7-9][0-9])|(2[0-9][0-9][0-9]))\/((0[1-9])|(1[0-2]))\/(([0-2][0-9])|(3[0-1]))\s(([0-1][0-9])|(2[0-4]))\:([0-5][0-9])\Z/, :message => "must be in this format: YYYY/MM/DD HH:MM" }

Edit: I figured out what the issue is, but I still don't know how to fix it...

For some reason when I submit my form the date 2014/12/24 16:19 is being cut down to just 2014. This then fails validation and throws the error.

Can anyone help me figure this out?

Community
  • 1
  • 1
daraul
  • 174
  • 5
  • 16
  • your regexp for ruby is correct, and it matches the provided string – Малъ Скрылевъ Dec 24 '14 at 17:58
  • Works for me: http://rubular.com/r/FoRXQm9t4H – August Dec 24 '14 at 18:04
  • @August I think my text_fields might be adding a new line to the end of the string. I tried adding a newline to the code you provided and it failed. Is there a way I can strip the newlines before submitting? – daraul Dec 24 '14 at 18:11
  • I think rails is cutting my input down to just the year for some reason. I don't know why, though – daraul Dec 24 '14 at 20:09
  • I figured out the problem: my datetime is being cut down to just the year (or anything before the first "/" I assumed) before being validated. Can anyone tell me why this is happening and how to get around it? – daraul Dec 24 '14 at 20:37

1 Answers1

1

Your regexp for ruby part is correct, and it matches the provided string:

re = /\A((19[7-9][0-9])|(2[0-9][0-9][0-9]))\/((0[1-9])|(1[0-2]))\/(([0-2][0-9])|(3[0-1]))\s(([0-1][0-9])|(2[0-4]))\:([0-5][0-9])\z/
'2014/12/02 11:06' =~ re # => 0 

Some notes:

  1. See the SO topics 1, 2, and 3 with explanation on how to match date in ruby.

  2. Use regexp online services rubular.com, or rubyxp.com to validate regexp match for ruby language, embedded app, or debug gem.

Community
  • 1
  • 1
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69