Forum Moderators: coopster

Message Too Old, No Replies

validating a date variable

validation in php

         

ksugam

12:00 am on Feb 14, 2008 (gmt 0)

10+ Year Member



Hello all,
I have a variable $month which uses GET to fetch the value user enters. now i want to make sure that the input is in the format:yyyy/mm

some valid e.g.: 2008/12, 2008/1, 2008/01

invalid examples: 2007/13, 20059/1

so basically i want to make sure tht there are 4 integers bfore the '/' , and there can be two intergers or 1 integer for month which should be less than 13...

Any help would be greatly appreciated....

thanks!

dreamcatcher

12:21 am on Feb 14, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi ksugam,

Looks like the way to go would be to explode [uk2.php.net] the var and then do some checks. If you had the full date you could use checkdate [uk2.php.net] to check for a valid date.

To check for digits you can use is_int [uk2.php.net], or the ctype_functions [uk2.php.net] or indeed character classes.

Good luck.

dc

ksugam

7:18 pm on Feb 15, 2008 (gmt 0)

10+ Year Member



i tried this:
$datearray=explode("/",$month);

if (is_int($datearray[0])){
do something
}

else exit;

It somehow does not seem to work...
can someone tell me whats happening?

ksugam

7:24 pm on Feb 15, 2008 (gmt 0)

10+ Year Member



i tried doing a var_dump for is_int($datearray[0]) (which is the year part of date) and it is giving me false as output....why is tht so?

PHP_Chimp

10:31 pm on Feb 15, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You may want to check your date using a regular expression. As "20059/1" is a valid date...just a long long way in the future.

As you want to check the pattern of your date you may want to use a regular expression -


$pattern = '%^\d{4}/(?:0?[1-9]¦1[012])$%';
if(!preg_match($pattern, $input)) {
echo 'Put in a proper date';
}

From what you asked it looks if you only want to check for this year then you could use something like -

$this_year = [url=http://uk2.php.net/manual/en/function.date.php]date[/url]('Y'); // 2008
$pattern = "%^$this_year/(?:0?[1-9]¦1[012])$%";

I dont know if that is actually what you want, just all of your examples were 2008, and you have a valid year in your invalid list (however I can understand why you are not bothered about a date 18051 years in the future ;)