Ruby: How to check if a string is a valid time?

Using Time.parse() is not a good solution, as shown in the example of the comments.

I'll leave the answer here for 'historical reasons', to keep the comments, and as a warning for future readers!


You can use Time.parse() and check for the ArgumentError exception for invalid times.

Extra advantage is that you also have the time in a usable format to work with if it is valid!


You haven't exactly specified what you assume to be a valid time (e.g. whether you should accept optional seconds), so here's one guess:

data =~ /^([01]?[0-9]|2[0-3])\:[0-5][0-9]$/