简体   繁体   中英

Validate date strings in Ruby with multiple accepted formats?

I have some strings that might or might not be dates like:

"Hello World", "Sept 12, 2013", "Hello World Sept 12"

In this case, I'd like only the second one to be considered a proper date.

So far, I have been using Date.parse and the Chronic gem but they very lenient and convert strings like "aa" or "12-UNKN/34/OWN1" into acceptable dates.

For example:

Date.parse '12-UNKN/34/OWN1'

would return:

 Tue, 12 Nov 2013

So, I am trying to restrict the accepted formats to a set of formats I can control:

09/12/2013
9/12/2013
9/12/13
09-12-2013
9-12-2013
9-12-13

and some formats with text inside like:

Sept 9, 2013 - with or without the coma, accepting Sep, Sept or September and with or without a dot after the month name, covering things like:
Sept. 9, 2013
Sept 09, 2013
Sept. 09, 2013
September 9, 2013
September 09, 2013

Any suggestion on a good way to do this in Ruby, either pure Ruby or with Rails?

I'll take a stab at this and elaborate on my comment. Separating the date from the other string allows you to validate the date in multiple formats before handing it off to Chronic:

validates_format_of :date, with: /\\d{2,4}[-/]\\d{1,2}[-/]\\d{1,4}/, on: :create

That should handle most of the date formats you described.

However, a big issue is you won't know if someone is submitting a date in the US format or non-US format.

The bigger issue is know what part of the title string is in fact a date, and that would either be a more complicated regular expression, or make it easy on yourself and make it a separate field. You're getting somewhat close to trying to parse natural language which isn't cut and dry by any means.

Try something like this

validate :validate_some_date

private

def validate_some_date
  errors.add("Created at date", "is invalid.") unless [
      date_case_one,
      date_case_two,
      date_case_three
    ].all?
end

def date_case_one
  # some regex
end

def date_case_two
  # some regex
end

def date_case_three
  # some regex
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM