mrg mrg - 4 months ago 14
Ruby Question

Date validation in Ruby

How to check if the date is valid date in ruby. Many of the methods are check only the range. But, I need to check the date with day of
week to check whether the date is valid or not. For Ex:

20 Jul 2016 Wed --> Valid
20 Jul 2016 Mon --> Not-Valid


How to do this in ruby ?

Answer

I'm not pretend on the best solution ever, but this should work.

def valid_date?(date)
  Date.parse(date).strftime("%d %b %Y %a") == date
end

[55] pry(main)> valid_date?("20 Jul 2016 Wed")
=> true
[56] pry(main)> valid_date?("20 Jul 2016 Mon")
=> false
[57] pry(main)>

If you have many formats you may pass format as a second argument

def valid_date?(date, fmt)
  Date.parse(date).strftime(fmt) == date
end

=> :valid_date?
[59] pry(main)> valid_date?("20 Jul 2016 Wed", "%d %b %Y %a")
=> true

Hope this will help.

UPDATE

As I mentioned in comment that method name overlaps with existing metod valid_date?

So, you may just rename the custom method

def date_valid?(date, fmt)
  Date.parse(date).strftime(fmt) == date
end

[2] pry(main)> date_valid?("20 Jul 2016 Wed", "%d %b %Y %a")
=> true