How to check if a string is a year

Ruby / RoR Usage - Year is a string in Model / View. How can I check that a user-entered string is a valid gregorian graphic year?

+2


source to share


6 answers


With a bit of feat / regex magic, something like the following will allow you to check not only if a string is numeric (first criteria for a valid year), but also if it falls within a specific 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 will return nil

for any string with non-numeric characters, false

for those that are numeric but outside the provided range, and true

for valid strings, the year.

+3


source


Seems like a more direct question: how do you validate that the user is entering a string that matches the number between 1582 and 2500 (say). You can do it like this:

 date_string.scan(/\D/).empty? and (1582..2500).include?(date_string.to_i)

      



so you can choose which is a reasonable year too, for example 800 is really a valid answer in your application? or 3000?

+5


source


Here's one way to do it:

Date.strptime(date_str, "%Y").gregorian?

      

Note that this will throw an exception if the string is in an unexpected format. Another (more forgiving) option:

Date.new(date_str.to_i).gregorian?

      

+4


source


@Rcoder's accepted answer won't work as I tested on rails 4+, I made another simple one.

def is_valid_year? year
  return false if year.to_i.to_s != year
  year.strip.to_i.between?(1800, 2999)
end

      

On the first line taking no characters, you can also change the range as you want

+3


source


Date.parse(string_of_date).gregorian?

      

Also, check out the documentation for the Date class .

0


source


0


source







All Articles