I have tried many ways of writing a validate date function in ruby which handles all the edge cases like , if the current date is valid according to leap year, and also if the date is passed in invalid format like 20-05-2022 it should return false , it should only valid format of date in yyyy-mm-dd format.
Functions I tried before asking here(this function I got from one of the Stackoverflow link):
require 'date'
def validate_date?(string)
date_format = '%Y-%m-%d'
DateTime.strptime(date, date_format)
true
rescue ArgumentError
false
end
But the problem with this function is it is not able to handle some of the invalid date formats like :
validate_date('202200-06-02') -> returns true (As the date is in incorrect format)
validate_date('2022-060-002') -> returns true (As the date is in incorrect format)
I want to return false if these invalid date formats are applied.
Any suggestions or improvements are welcome, or even what else should I try to write a proper validate_date function which can be used for all kinds of edge cases.
CodePudding user response:
If you are using Rails you can use method to_date
in combination with regexp
def valid_date?(string)
!!(string.to_date && /^\d{4}-\d{1,2}-\d{1,2}$/ =~ string)
rescue Date::Error
false
end
If you are not
require 'date'
def valid_date?(string)
!!(Date.parse(string) && /^\d{4}-\d{1,2}-\d{1,2}$/ =~ string)
rescue Date::Error
false
end