Php date validate


/ Published in: PHP
Save to your folder(s)

PHP provides many date manipulation devices and an entire suite of date functionality with the datetime class. However, this does not address date validation, that is, what format a date is received in. The PHP strtotime() function will accept many forms of dates in most human readable strings. The issue with strtotime is that there is no way to account for differing date formats, eg: 12/05/2010. Depending on what country a user is from, this date could have several meanings, such as which is the month, and which is day field. By splitting the date into its respective fields, each segment can be checked with the PHP checkdate function. The function below validates a date by splitting the date in year, month, day and using these as arguments to checkdate.


Copy this code and paste it in your HTML
  1. <?php
  2. /**
  3.   *
  4.   * Validate a date
  5.   *
  6.   * @param string $date
  7.   * @param string format
  8.   * @return bool
  9.   *
  10.   */
  11. function validateDate( $date, $format='YYYY-MM-DD')
  12. {
  13. switch( $format )
  14. {
  15. case 'YYYY/MM/DD':
  16. case 'YYYY-MM-DD':
  17. list( $y, $m, $d ) = preg_split( '/[-\.\/ ]/', $date );
  18. break;
  19.  
  20. case 'YYYY/DD/MM':
  21. case 'YYYY-DD-MM':
  22. list( $y, $d, $m ) = preg_split( '/[-\.\/ ]/', $date );
  23. break;
  24.  
  25. case 'DD-MM-YYYY':
  26. case 'DD/MM/YYYY':
  27. list( $d, $m, $y ) = preg_split( '/[-\.\/ ]/', $date );
  28. break;
  29.  
  30. case 'MM-DD-YYYY':
  31. case 'MM/DD/YYYY':
  32. list( $m, $d, $y ) = preg_split( '/[-\.\/ ]/', $date );
  33. break;
  34.  
  35. case 'YYYYMMDD':
  36. $y = substr( $date, 0, 4 );
  37. $m = substr( $date, 4, 2 );
  38. $d = substr( $date, 6, 2 );
  39. break;
  40.  
  41. case 'YYYYDDMM':
  42. $y = substr( $date, 0, 4 );
  43. $d = substr( $date, 4, 2 );
  44. $m = substr( $date, 6, 2 );
  45. break;
  46.  
  47. default:
  48. throw new Exception( "Invalid Date Format" );
  49. }
  50. return checkdate( $m, $d, $y );
  51. }
  52. ?>
  53. /* example usage*/
  54.  
  55. <?php
  56. echo validateDate( '2007-04-21' ) ? 'good'. "\n" : 'bad' . "\n";
  57. echo validateDate( '2007-21-04', 'YYYY-DD-MM' ) ? 'good'. "\n" : 'bad' . "\n";
  58. echo validateDate( '2007-21-04', 'YYYY/DD/MM' ) ? 'good'. "\n" : 'bad' . "\n";
  59. echo validateDate( '21/4/2007', 'DD/MM/YYYY' ) ? 'good'. "\n" : 'bad' . "\n";
  60. echo validateDate( '4/21/2007', 'MM/DD/YYYY' ) ? 'good'. "\n" : 'bad' . "\n";
  61. echo validateDate( '20070421', 'YYYYMMDD' ) ? 'good'. "\n" : 'bad' . "\n";
  62. echo validateDate( '04212007', 'YYYYDDMM' ) ? 'good'. "\n" : 'bad' . "\n";
  63. ?>

URL: http://www.phpro.org/examples/Validate-Date-Using-PHP.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.