简体   繁体   English

使用多种可接受的格式验证Ruby中的日期字符串吗?

[英]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. 到目前为止,我一直在使用Date.parse和Chronic gem,但是它们非常宽松,可以将"aa""12-UNKN/34/OWN1"类的字符串转换为可接受的日期。

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? 是否有建议在Ruby中(纯Ruby或与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: 将日期与其他字符串分开,可让您在将日期交给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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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