proud Posted May 30, 2009 Share Posted May 30, 2009 I want to write a php code to validate a date string which has to be in the format:mmyy, for example (0308).. where 03 is (march) and 08 is (2008). months can range from 01 - 12, for example 13 is not acceptable: 1309.. Also months from january till september has to start with a 0: 0109,0209,0309 etc... finally i want to make sure that the provided string does not exceed the current year and month, for instance 0509 is accepted but 0609 or 0310 must be rejected. I don't know which php function can be used for such a validation, any help would be appreciated. Quote Link to comment Share on other sites More sharing options...
will35010 Posted May 30, 2009 Share Posted May 30, 2009 Will this PEAR package work for you? It has date validation. http://pear.php.net/package/Validate/docs/0.8.2/Validate/Validate.html Quote Link to comment Share on other sites More sharing options...
Michdd Posted May 30, 2009 Share Posted May 30, 2009 Only having the 2 number-representation of the year won't allow you to check if the year is valid. Because say the year is 1993, it would be 93. But the 2 number for 2009 is 09, and 93 > 09. You need to know the full year. Besides that you can do something like this (to get you started): function valid_date($date) { $now = str_split(date('my'), 2); $date = str_split($date, 2); if($date[0] > 12) //If the month is over 12. { return false; } return true; } $date = 0308; if(valid_date($date) { echo 'The date is valid!'; } else { echo 'Invalid Date!'; } Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted May 30, 2009 Share Posted May 30, 2009 There isn't a PHP function that handles your specific case. At least not one I know of. It wouldn't make sense to represent a date as such anyways. <?php function validDate ($date, $current_month, $current_year) { if (strlen($date) !== 4) return false; $month = substr($date, 0, 2); $year = substr($date, 2, 2); return intval($month) <= intval($current_month) && intval($year) <= intval($current_year); } $valid_date = '0509'; $invalid_date = '0609'; $invalid_date2 = '1309'; $invalid_date3 = '109'; $current_month = date('m'); $current_year = date('y'); echo $valid_date . 'is ' . (validDate($valid_date, $current_month, $current_year)? 'valid' : 'invalid') . "\n"; echo $invalid_date . 'is ' . (validDate($invalid_date, $current_month, $current_year)? 'valid' : 'invalid') . "\n"; echo $invalid_date2 . 'is ' . (validDate($invalid_date2, $current_month, $current_year)? 'valid' : 'invalid') . "\n"; echo $invalid_date3 . 'is ' . (validDate($invalid_date3, $current_month, $current_year)? 'valid' : 'invalid') . "\n"; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.