Reputation: 23
I am trying to validate proper date input in my ruby script.
When I run the script it just asks for the date twice no matter if it is correct or not.
Could someone please tell me where I went wrong?
def get_date(prompt="What is the date of the last scan (YYYYMMDD)")
new_regex = /\A[0-9]{4}[0-1][0-9][0-3][0-9]\z/
print prompt
gets.chomp
if prompt != new_regex
puts "Please enter the date in the correct format"
print prompt
gets.chomp
end
end
Upvotes: 2
Views: 269
Reputation: 5363
Your code, as it is, is trying to compare the likeness of the prompt to the regex pattern.
/\A[0-9]{4}[0-1][0-9][0-3][0-9]\z/ === /\A[0-9]{4}[0-1][0-9][0-3][0-9]\z/
is true.
Your input is also not being captured, and thus not compared to the regex.
def get_date(prompt="What is the date of the last scan")
new_regex = /\A[0-9]{4}[0-1][0-9][0-3][0-9]\z/
print prompt + " (YYYYMMDD)"
input = gets.chomp
unless (input =~ new_regex) == 0
puts "Please enter the date in the correct format"
get_date(prompt)
end
input
end
input =~ new_regex
will be nil (false) if there's no match.
(ps Rubyists like two spaces)
Upvotes: 0