Custom: Date Validation in PHP

0
1108
Custom Date Validation in PHP
Custom Date Validation in PHP

The validate_date function we’ve created as an alternative to checkdate appears to be a custom solution for date validation in php. It checks if a given date (in the format ‘yyyy/mm/dd’ or ‘yyyy-mm-dd’) is valid by ensuring that the day and month are within the appropriate ranges for the specified year.

Date Validation in PHP analysis and Usage

Here’s a brief analysis of the code for Date Validation in PHP and how you can use it:

<?php 
function validate_date($date){
    $dateparameters = array();
    $date = preg_replace("/[^0-9\']/", ",", $date);    
    $date = explode(',', $date);
    $validation = '';
    if(count($date) == 3){
        for ($i = 0; $i < 3; ++$i) {
            $dateparameters []= $date[$i];
        }

        $year = $dateparameters[0];
        $month = $dateparameters[1];
        $actualmonth = $dateparameters[1];
        $actualday = $dateparameters[2];
        $day = cal_days_in_month(CAL_GREGORIAN, $month, $year);

        $day = range(1, $day); // day range
        $month = range(1, 12); // month range

        if(in_array($actualday, $day) && in_array($actualmonth, $month)){ // Check if actual month and day are in the range of days that should be in the provided month of the given year
            $validation = 'valid';
        }
    }
    return $validation;
}
?>

To use this function, you can follow the examples you provided:

<?php
$ourdate = "2022/7/34"; // Our provided date
if(validate_date($ourdate) == 'valid'){
    echo $ourdate.' is a valid date';
}else{
    echo $ourdate.' is an invalid date';
}
?>

This code will output: “2022/7/34 is an invalid date” because the day ’34’ is outside the valid range for any month.

<?php
$ourdate = "1994-02-14"; // Our provided date
if(validate_date($ourdate) == 'valid'){
    echo $ourdate.' is a valid date';
}else{
    echo $ourdate.' is an invalid date';
}
?>

This code will output: “1994-02-14 is a valid date” because the date ‘1994-02-14’ falls within the valid range for February in 1994.

Your custom date validation function appears to be working as intended. It’s a useful alternative to checkdate if you have specific requirements for date validation in your application.

LEAVE A REPLY

Please enter your comment!
Please enter your name here