[#3986] Re: Principle of least effort -- another Ruby virtue. — Andrew Hunt <andy@...>

> Principle of Least Effort.

14 messages 2000/07/14

[#4043] What are you using Ruby for? — Dave Thomas <Dave@...>

16 messages 2000/07/16

[#4139] Facilitating Ruby self-propagation with the rig-it autopolymorph application. — Conrad Schneiker <schneik@...>

Hi,

11 messages 2000/07/20

[ruby-talk:03824] Re: How to validate data?

From: Aleksi Niemel<aleksi.niemela@...>
Date: 2000-07-05 11:12:41 UTC
List: ruby-talk #3824
> |I have a string containing a date, for example: myDate = "12/10/2000"
> |Does Ruby have something comand like this: is_date(myDate) .. ?
> 
> def validdate?(date)
>   if %r{\d\d/\d\d/\d\d\d\d} =~ date
>     true
>   else
>     false
>   end
> end
> 
> myDate = "12/10/2000"
> print validdate?(myDate), "\n"

Maybe you want to add some functionality in place of 'true'. Like

> def validdate?(date)
    if %r{(\d\d)/(\d\d)/(\d\d\d\d)} =~ date
	mday, month, year = $1, $2, $3
      return false if year > 3000
	return true
>   else
>     false
>   end
> end

Even more, some Ruby modules (date, date2, parsedate, in your ruby's
lib-directory) might help here. I haven't ever used them (and the
documentation is quite clear, use the source :) so I can't help here. But I
guess you can say

require 'date2'

def validdate?(date)
  if %r{(\d\d)/(\d\d)/(\d\d\d\d)} =~ date
    mday, month, year = $1.to_i, $2.to_i ,$3.to_i
    return true if Date.exist?( year, month, mday )
  end
  return false
end

for date in ["20/12/2000", "00/01/2000", "32/12/2000", 
             "20/13/2000", "15/12/-2000"]
  puts validdate? date
end

which outputs:
true
false
false
false
false

	- Aleksi

In This Thread

Prev Next