Using Ruby/RoR - The year is a string in the model/view. How do I validate that the user entered string is a valid gregorian calendar year?
Date.parse(string_of_date).gregorian?
Also, have a look at the documentation for the Date class.
It sounds like a more direct question is: how do you validate that the user enters a string corresponding to a number between 1582 and 2500 (say). You can do this like this:
date_string.scan(/\D/).empty? and (1582..2500).include?(date_string.to_i)
that way, you can choose what a sensible year is, too - for example, is 800 really a valid answer in your application? or 3000?
Here's one way to do it:
Date.strptime(date_str, "%Y").gregorian?
Note that this will throw exceptions if the string is in an unexpected format. Another (more forgiving) option, is:
Date.new(date_str.to_i).gregorian?
At the cost of a tiny bit of cleverness/regexp magic, something like the following will allow you to test not only for whether a string is numeric (the first criteria for being a valid year) but for whether it falls within a particular range of years:
def is_valid_year?(date_str, start=1900, end=2099)
date_str.grep(/^(\d)+$/) {|date_str| (start..end).include?(date_str.to_i) }.first
end
The above function returns nil
for any string with non-numeric characters, false
for those which are numeric but outside the provided range, and true
for valid year strings.
Wanting to parse an integer from a string is a pretty common question for Ruby. Probably because there's no perfect approach. Maybe it deserves its own tag!
http://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby
http://stackoverflow.com/questions/1060300/how-do-i-get-the-second-integer-in-a-ruby-string-with-toi