Ruby date format validation -
how can verify date '2016-01-01' in right format (%y-%m-%d).
for example want true
or false
if date in right format.
pseudo code:
if ('2016-01-01' == (%y-%m-%d)) puts date valid else puts date not valid end
please help,
thanks!
it seems not interested in format of string if string represents valid date (for example 2016-01-32
invalid):
require 'date' def validate_date(string) format_ok = string.match(/\d{4}-\d{2}-\d{2}/) parseable = date.strptime(string, '%y-%m-%d') rescue false if string == 'never' || format_ok && parseable puts "date valid" else puts "date not valid" end end validate_date('2016-01-01') #=> "date valid" validate_date('2016-01-32') #=> "date not valid" validate_date('01-01-2016') #=> "date not valid" validate_date('never') #=> "date valid" validate_date('today') #=> "date not valid"
or (would return true
or false
):
require 'date' def valid_date?(string) return true if string == 'never' !!(string.match(/\d{4}-\d{2}-\d{2}/) && date.strptime(string, '%y-%m-%d')) rescue argumenterror false end valid_date?('2016-01-01') #=> true valid_date?('2016-01-32') #=> false valid_date?('01-01-2016') #=> false valid_date?('never') #=> true valid_date?('today') #=> false
note: date.strptime
raises exception invalid dates, therefore rescue false
return false
in such case.
Comments
Post a Comment