0

I'm trying to make a user registration. I just want to ask about the date using 3 inputs type="text" how to sanitize the Month, Day, and Year using PHP. If the month of February is a leap year or Month of November is only 30 days and the user input 31. Thanks guys!

if (isset($_POST['submit'])) {
    $yy = preg_replace('#[^0-9]#i','',$_POST['yy']);
    $mm = preg_replace('#[^0-9]#i','',$_POST['mm']);
    $dd = preg_replace('#[^0-9]#i','',$_POST['dd']);
    if ($mm > 12) {
        $error[] = 'Invalid month.';
    } else if ($dd > 31) {
        $error[] = 'Invalid day.';
    } else if (strlen($yy) < 4) {
        $error[] = 'Invalid year.';
    }
}
Digital Alchemist
  • 2,324
  • 1
  • 15
  • 17
Christopher Rioja
  • 149
  • 2
  • 2
  • 10

3 Answers3

0

The checkdate function may what you're looking for: http://www.php.net/manual/en/function.checkdate.php

if (checkdate(intval($mm) . ',' . intval($dd) . ',' .  intval($yy))) echo 'valid!';  
malcanso
  • 100
  • 2
  • 7
0

examle if date is correct returns true else false

 <?php
    var_dump(checkdate(12,31,-400));  ///bool(false)
    echo "<br>";
    var_dump(checkdate(2,29,2003));  ////bool(false)
    echo "<br>";
    var_dump(checkdate(2,29,2004));  ////bool(true)
    ?>
user2092317
  • 3,226
  • 5
  • 24
  • 35
0

The following regular expression can verify correct and incorrect date, but u need some refactoring of code i.e

Valid date parse by below regex "2013-09-12";

$date = $_POST['yy'].'-'.$_POST['mm'].'-'.$_POST['dd'];

or

$date = $yy.'-'.$mm.'-'.$dd';   // after retrieving values of month, year, day

if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date))
{
    return true; // date is valid in above define format
}else{
    return false; // invalid date
}

or using Php CheckDate function, it Checks the validity of the date

bool checkdate ( int $month , int $day , int $year )
Digital Alchemist
  • 2,324
  • 1
  • 15
  • 17
  • I use this code and it return false. Format yy-mm-dd "1992-10-5" if (preg_match('#^(\d{4})-(\d{2})-(\d{2})$#',$releasedate, $matches) && checkdate($matches[2], $matches[3], $matches[1])) { return true; } else { $error[] = 'Release date does not appear valid.'; return false; } – Christopher Rioja Oct 04 '13 at 18:50
  • My inputs are "MM-DD-YYYY", I input these "10-5-1992" and it returns an error message may code $yy = preg_replace('#[^0-9]#i','',$_POST['yy']); $mm = preg_replace('#[^0-9]#i','',$_POST['mm']); $dd = preg_replace('#[^0-9]#i','',$_POST['dd']); $releasedate = $yy.'-'.$mm.'-'.$dd; if (preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/",$releasedate,$matches) && checkdate($matches[1],$matches[2],$matches[0])) { return true; } else { $error[] = 'Release date does not appear valid.'; } – Christopher Rioja Oct 04 '13 at 19:53