SitePoint Sponsor

User Tag List

Results 1 to 19 of 19

Thread: Date validation

  1. #1
    SitePoint Wizard billy_111's Avatar
    Join Date
    Jul 2009
    Posts
    1,683
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Date validation

    Hey,

    I am trying to validate the date on the following page:-

    http://www.judgethejob.com/vinny/submit-review/

    If you find the question "Are you a past or present employee?*"

    And click on "past", you will see a start date and an end date. How can i validate these so that users can not put a date before the start date?

    Basically i dont want the user to be able to select and end date that is before the start date..

    Regards

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,578
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    if ($_POST['L_Year'] < $_POST['S_Year'] || ($_POST['L_Year'] == $_POST['S_Year'] && $_POST['L_Month'] < $_POST['S_Month'])) {
      
    //invalid

    In words: If the leave year is before the start year, OR if the leave year and the start year are equal and the leave month is before the start month.

  3. #3
    SitePoint Wizard billy_111's Avatar
    Join Date
    Jul 2009
    Posts
    1,683
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks!

    I didnt think i could simply say if one is bigger than the other, i thought i would have to change the date format and then try validating.



    Regards

  4. #4
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,578
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Actually this won't work. I didn't look at your form and assumed the values of your <select> lists were numbers, as is usually the case.

    If you have a good reason for using strings there, converting to numbers for comparison is easy:

    PHP Code:
    $months = array(
    'January' => 1,
    'February' => 2,
    'March' => 3,
    'April' => 4,
    'May' => 5,
    'June' => 6,
    'July' => 7,
    'August' => 8,
    'September' => 9,
    'October' => 10,
    'November' => 11,
    'December' => 12);

    $month_number $months[$name]; 

  5. #5
    SitePoint Wizard billy_111's Avatar
    Join Date
    Jul 2009
    Posts
    1,683
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, what i do with the date as strings is store them into a a session variable. And then pass them across a page, then insert them into a database so i would need them as strings.

    So if i use the code you suggested would the date be added as a number or the string?

    And would i convert before i store them into a session?

    I currently do this when storing them into a session:-

    $_SESSION['S_Month'] = $_POST['S_Month'];
    $_SESSION['S_Year'] = $_POST['S_Year'];
    $_SESSION['L_Month'] = $_POST['L_Month'];
    $_SESSION['L_Year'] = $_POST['L_Year'];
    So where would i need to do the conversion?

    Regards

  6. #6
    Non-Member
    Join Date
    Oct 2009
    Posts
    1,852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you can easily compare dates as strings
    PHP Code:
    $start_date "2009-11-11";
    $check_date "2009-11-22";
    if (
    $check_date $start_date) echo "Bad boy! Don't lie to mommy!"

  7. #7
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,578
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by billy_111 View Post
    Well, what i do with the date as strings is store them into a a session variable. And then pass them across a page, then insert them into a database so i would need them as strings.
    Why does any of that require it to be a string?

    Quote Originally Posted by billy_111 View Post
    So if i use the code you suggested would the date be added as a number or the string?
    A number to compare the months.

    Quote Originally Posted by billy_111 View Post
    And would i convert before i store them into a session?
    You do not need to store anything as part of this task, form validation code happens on the page that processes the form, not some other page. Comparing the numeric representation of the month doesn't stop you from storing the string representation of the month elsewhere in the code.

    Quote Originally Posted by Shrapnel_N5
    you can easily compare dates as strings
    The form being validated doesn't contain any dates though, it has <select> lists of months and years.

  8. #8
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,631
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    strtotime() is also an option.

    PHP Code:
    <?php
    date_default_timezone_set
    ("Europe/London");
    $start strtotime ("November 2008");
    $end strtotime ("March 2009");

    echo 
    "$start : $end : ";

    echo (
    $end $start) ? "yes" "no";
    ?>
    Ian Anderson
    www.siteguru.co.uk

  9. #9
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you just need to compare them, format the date in ISO format and use string compare. If you need to do anything more than that, use the database. Time is deceptive in that it appears simple, but has a lot of hidden complexities.

  10. #10
    Floridiot joebert's Avatar
    Join Date
    Mar 2004
    Location
    Kenneth City, FL
    Posts
    823
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    $_SESSION['L_Year'] = $_POST['L_Year'];
    As soon as I saw that I got a knot in my stomach. Once I submitted your form with the following as the company name I discovered my knot may be for good reason.

    Code:
    <script type="text/javascript">alert('');</script>
    If your date fields work anything like your company name field, the start date being later than end date might be the least of your worries.

    By the time you get done validating the date input to make sure it's even a date to begin with, determining if one is earlier than the other should have an obvious solution.

  11. #11
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,053
    Mentioned
    66 Post(s)
    Tagged
    1 Thread(s)
    Personally I do date input as an array on the form in html, like so.

    PHP Code:
    <select name="myDate[year]">
    <?php for ($i intval(date('Y')); $i 1990$i--): ?>
    <option value="<?php echo $i ?>"><?php echo $i ?></option>
    <?php endfor ?>
    </select>
    <select name="myDate[month]">
    <?php foreach( $monthArray as $monthNumber => $monthName): ?>
    <option value="<?php echo $monthNumber ?>"><?php echo $monthName ?></option>
    <?php endforeach ?>
    </select>
    <select name="myDate[date]">
    <?php for ($i 1$i <= 31$i++): ?>
    <option value="<?php echo $i ?>"><?php echo $i ?></option>
    <?php endfor ?>
    </select>
    The code above requires that you define an associative array with the months of the year indexed 1 through twelve. Now, when you receive the form you'll get a array named $_POST['myDate'] that has each three elements. No string splitting or toying necessary from here on out, you can get a timestamp with

    PHP Code:
    $timestamp strtotime($_POST['myDate']['year'].'-'.$_POST['myDate']['month'].'-'.$_POST['myDate']['date']); 
    Once the date is a timestamp comparisons are trivial. Remember that strtotime returns false if they select 31 for the day in February - that's about the only way they can much this form up. I personally use javascript to repopulate the date column as determined by the month selected to prevent this, but since the client can block javascript it is imperative that you check for this server side and have response code ready for an invalid date.

  12. #12
    SitePoint Zealot Dorsey's Avatar
    Join Date
    Feb 2004
    Location
    NJ
    Posts
    103
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    We use a Javascript calendar selector to ensure valid dates, but if you must do it the old way, I'd agree with computerstar to some extent. However you obtain date strings, the simple way to both validate the date and range is to convert both dates to *nix time and do a simple compare on the resultant integers.

    // combine date components into MM/DD/YYYY (US format) in $strDate
    if( ( $intEarlyDate = strototime( $strDate ) ) === false )
    echo "bad date";
    else
    echo "number of seconds since the *nix Epoch: $intEarlyDate";

    When both have validated:

    if( $intEarlyDate >= $intLateDate )
    echo "Bad date range";
    else
    echo "Date range is plausible";

  13. #13
    SitePoint Member temmokan's Avatar
    Join Date
    Dec 2009
    Location
    Novosibirsk, Russia
    Posts
    23
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Under certain circumstances the following will do: compare integer numbers "yyyymmdd" for every date.

    The most reliable way is, though, first check the date is correct via checkdate($month,$day,$year), then convert dates to the above integers and compare.

  14. #14
    SitePoint Addict eanimator's Avatar
    Join Date
    Sep 2005
    Posts
    396
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    function check_date($date) {
            if(
    strlen($date) == 10) {
                
    $pattern '/\.|\/|-/i';    // . or / or -
                
    preg_match($pattern$date$char);
               
                
    $array preg_split($pattern$date, -1PREG_SPLIT_NO_EMPTY);
               
                if(
    strlen($array[2]) == 4) {
                    
    // dd.mm.yyyy || dd-mm-yyyy
                    
    if($char[0] == "."|| $char[0] == "-") {
                        
    $month $array[1];
                        
    $day $array[0];
                        
    $year $array[2];
                    }
                    
    // mm/dd/yyyy    # Common U.S. writing
                    
    if($char[0] == "/") {
                        
    $month $array[0];
                        
    $day $array[1];
                        
    $year $array[2];
                    }
                }
                
    // yyyy-mm-dd    # iso 8601
                
    if(strlen($array[0]) == && $char[0] == "-") {
                    
    $month $array[1];
                    
    $day $array[2];
                    
    $year $array[0];
                }
                if(
    checkdate($month$day$year)) {   
                    return 
    TRUE;
               
                } else {
                    return 
    FALSE;
                }
            }else {
                return 
    FALSE;
            }
        } 

  15. #15
    SitePoint Wizard billy_111's Avatar
    Join Date
    Jul 2009
    Posts
    1,683
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey,

    So if you look at the page i am working on, if you click on the "past" radio button you will see the four drop down list boxes appearing.

    Now i have them like so:-

    PHP Code:
                        <select name="S_Month" class="formlist" id="ValidMonth">
                            <
    option value "January">January</option>
                            <
    option value "February">February</option>
                            <
    option value "March">March</option
    And year like so:-

    PHP Code:
                                <select name="S_Year" id="ValidYear">

                            <
    option value="2007">2009</option>
                            <
    option value="2007">2008</option
    I have four drop downs S_Month, S_Year, L_Month, L_Year..

    Is there a way i can compare these in the ways you guys gave suggested?

    How would i actually apply each drop down?

  16. #16
    Non-Member
    Join Date
    Oct 2009
    Posts
    1,852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    First, change month values to numbers with leading zero's.
    Second, concat all date values into string of format YYYY-MM-DD
    And, finally, compare.

  17. #17
    SitePoint Wizard billy_111's Avatar
    Join Date
    Jul 2009
    Posts
    1,683
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well lets say i wanted to use the moths array:-

    PHP Code:
                            <?
                            $months 
    = array(
                            
    'January' => 1,
                            
    'February' => 2,
                            
    'March' => 3,
                            
    'April' => 4,
                            
    'May' => 5,
                            
    'June' => 6,
                            
    'July' => 7,
                            
    'August' => 8,
                            
    'September' => 9,
                            
    'October' => 10,
                            
    'November' => 11,
                            
    'December' => 12);
                            
                            
    $month_number $months[$name]; 
                            
    ?>

                            <select name="S_Month" class="formlist" id="ValidMonth">            
                            <option value = "January">January</option>
    </select>
    how can i apply $months to the drop down list box. I need to values in the dropdowns as strings as i need to pass it in a variable on another page..

  18. #18
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    By using foreach to iterate through the keys in the array.

    Code php:
    $monthOptions = '';
    foreach ($months as $key => $dummy) {
        $month = htmlentities($key);
        $monthOptions .= '<option value="'.$month.'">'.$month.'</option>'; 
    }
    <select name="S_Month" class="formlist" id="ValidMonth">             
    <?php echo $monthOptions; ?>
    </select>

    You could also optionally use array_keys

    Code php:
    $monthOptions = '';
    $monthNames = array_keys($months);
    for ($i = 0; $i < count($monthNames); $i++) {
        $month = htmlentities($monthNames[$i]);
        $monthOptions .= '<option value="'.$month.'">'.$month.'</option>'; 
    }
    <select name="S_Month" class="formlist" id="ValidMonth">             
    <?php echo $monthOptions; ?>
    </select>
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  19. #19
    SitePoint Wizard billy_111's Avatar
    Join Date
    Jul 2009
    Posts
    1,683
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •