SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict
    Join Date
    Sep 2002
    Posts
    225
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Checking for a valid date?

    I've been doing a bit of research and haven't found anything too easy. Can anyone point me to an article that has a function written in javascript that validates that a date that has been submitted via a form that it is a valid date?

    Thanks!

  2. #2
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've been doing a bit of research and haven't found anything too easy
    Then post the specific format you want to validate against and hopefully someone will be able to help you.

  3. #3
    SitePoint Addict
    Join Date
    Sep 2002
    Posts
    225
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well I have three drop downs on my page. One for month, one for year, one for day.

    Right now I have this function to check the date:

    Code:
    function check_date(month, day, year) {
        // month, day, year are all ints.
        return true;
    }
    Obviously, I don't know what exactly to put in the guts of the function. =/

    Thanks!

  4. #4
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,862
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    var d = new Date(year,month,day);
    if (d.getDate() != day || d.getMonth() != month) return false;
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  5. #5
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's always best to not offer an option that isn't valid.

    You have three select fields, for year, date and month.
    Add an onchange event to the year and month selects,
    and add or delete days in the date menu according to the
    allowable number of days for the selected month and year.

    I'd also use felgalls approach to validate on the server,
    for those folks who don't have scripting enabled and so have 31 days to choose from in every month.

    This may be helpful-
    Code:
    Date.prototype.monthDays= function(){
    	var m= this.getMonth()+1;
    	switch(m){
    		case 4: case 6: case 9: case 11: return 30;
    		case 2:
    		var dy= this.getFullYear();
    		if(dy&#37;400 ==0 || (dy%100 !=0 && dy%4==0)) return 29;
    		return 28;
    		default: return 31;
    	}
    }


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
  •