SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Jan 2005
    Posts
    114
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Date Validation against today's date

    hello all,

    I need some help with something and I am sure that its a simple task:

    I want to check the date of a field (in a form) against the date on the computer....if the date selected (from the popup calendar) is after today's date, the person will get an error message. Otherwise, it let's them proceed.

    Here is what I tried (and if you'r a pro, don't laugh at my attempt):

    var thisDate = new Date();
    if (document.claims.DateofLoss.value < thisDate)
    {
    alert ("Please select a date before today's date!");
    return false;
    }
    return true;

    Didn't work. lol.

    Please help!!
    Thank you.

  2. #2
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    You can do date arithmetic by just subtracting two dates:

    var today = new Date();
    var entered = new Date("2-1-2005");
    var result = today - entered;
    alert(result);

    Internally, each date is the number of milliseconds since 1970. So, the alert() will display the number of milliseconds between the two dates. Therefore, if the result is positive, the entered date was in the past.

    The problem you might have is converting the date entered into your form into a format that the Date() object can understand for the line:

    var entered = new Date("2-2-2005");

    The Date object can handle a number of different formats, e.g.

    "2 February 2005"
    "February 2 2005"

    First, try the format of the date that is entered in the form, and if that doesn't work, you are going to have to convert it to an acceptable format. In addition, I imagine people can just type in a date without using your calendar, and therefore they could type in the date in any format, which you are going to have to deal with. Doing form validation to make sure a user entered something properly is never easy. Search for 'javascript form validtion' for more info.


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
  •