How to validate a date format using PHP

H

How Can We Help?

How to validate a date format using PHP

To check whether the date entered is in the correct format

NOTE: We will use the following date format within this example YYYY-MM-DD

Answer:

  • Use the preg_match ‘Perform a regular expression match’  PHP function available for PHP 4 & 5 
  • Find the correct expression
  • And use the following code to check for the date format
    if(preg_match('/[12]\d{3}-[01]\d-[0123]\d/',$date)){
        $msg = "Valid date";
    }else{
        $msg = "Invalid date";
    }

About the author

Ian Carnaghan

I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment.

About Author

Ian Carnaghan

I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment.

Follow Me