Date validation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ghjk
    Contributor
    • Jan 2008
    • 250

    Date validation

    I want to validate Date in my php application. User should select a date by clicking on calander icon or typinig. I want to check whether the date is in "2008-07-01" format. How can i do that? Could some one help me?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    You could use a simple regular expression for that validation.

    Comment

    • nashruddin
      New Member
      • Jun 2008
      • 25

      #3
      try this:

      Code:
      <?php
      $date_in = '2008-07-01';
      list($year, $month, $day) = explode('-', $date_in);
      
      if (checkdate($month, $day, $year)) {
        echo 'date valid.';
      } else {
        echo 'date invalid';
      }

      Comment

      • dlite922
        Recognized Expert Top Contributor
        • Dec 2007
        • 1586

        #4
        Originally posted by nashruddin
        try this:

        Code:
        <?php
        $date_in = '2008-07-01';
        list($year, $month, $day) = explode('-', $date_in);
        
        if (checkdate($month, $day, $year)) {
          echo 'date valid.';
        } else {
          echo 'date invalid';
        }
        nice, but regex would be faster.

        Here's one that checks for February dates range 0-29:

        Code:
        
        
        preg_match("/^(19|20)?[0-9]{2}[-/ \\.]((0?[13-9]|1[012])[-/ \\.](0?[1-9]|[12][0-9]|3[01])|(0?2[-/ \\.][012]?[0-9]))$/",$variable);
        if you don't care about February 30 / 31 date checking try this:

        Code:
        preg_match("/^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$/",$variable);
        please let me know if there's any problems in the first one, I hand coded it myself.


        -Dan

        Comment

        Working...