Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 3 123 LastLast
Results 1 to 15 of 45
  1. #1
    New Coder
    Join Date
    Jun 2009
    Posts
    95
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Validate Date field MM/DD/YYYY with legit date

    Hi All,

    I've been searching all over the web and plugging in pieces of code that I have found that would accomplish a field validation maknig sure the date is in the right format and it is an actual date. Not 12/45/2012.

    This is the latest piece of code I've taken from the web but this still isn't working:

    Code:
    function isValidDate(dateString)
    {
        // First check for the pattern
        if(!/^\d{2}\/\d{2}\/\d{4}$/.test(dateString))
            return false;
    
        // Parse the date parts to integers
        var parts = dateString.split("/");
        var day = parseInt(parts[1], 10);
        var month = parseInt(parts[0], 10);
        var year = parseInt(parts[2], 10);
    
        // Check the ranges of month and year
        if(year < 1000 || year > 3000 || month == 0 || month > 12)
            return false;
    
        var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
    
        // Adjust for leap years
        if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
            monthLength[1] = 29;
    
        // Check the range of the day
        return day > 0 && day <= monthLength[month - 1];
    }
    And I also have:

    Code:
    function validateForm( frm )
    {
    	var oops = "";
    	var apptype = getRBValue( frm.elements["MoveType."] );
        if ( apptype == null )
            oops += "You must check Temporary or Permanent.\n";
    	var apptype = getRBValue( frm.elements["ResSummer."] );
        if ( apptype == null )
            oops += "You must check Yes or No for residential summer student.\n";
        if ( trim( frm.elements["FirstName."] ).length  < 2 )
            oops += "You must enter your First name.\n";
        if ( trim( frm.elements["LastName."] ).length  < 2 )
            oops += "You must enter your Last name.\n";
        if ( ! emailCheck( frm.elements["Email."] ) )
            oops += "That does not appear to be a valid Email Address.\n";
    	if (trim( frm.elements["Box."] ).length  < 1 || trim( frm.elements["Box."] ).length > 4)
            oops += "You must enter a Box# (Max 4 digits).\n";
        if ( ! isValidDate( frm.elements["EffectiveDate."] ) )
            oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";	
    if ( trim( frm.elements["StreetAddress."] ).length  < 5 )
            oops += "You must enter your Street Address.\n";
    	if ( trim( frm.elements["City."] ).length  < 4 )
            oops += "You must enter your City.\n";
        if ( trim( frm.elements["State."] ).length  < 1 )
            oops += "You must enter your State.\n";
    	if ( ! zipCheck( frm.elements["Zip."] ) )
            oops += "You must enter a 5 digit Zip Code.\n";
        // additional building and room are not validated, but they are are trimmed and upper cased
        trim(frm.Apt);
    	
        
        var inps = frm.elements;
        var chkbx = false;
        for ( var i = 0; i < inps.length; ++i )
        {
            var inp = inps[i];
            if ( inp.name.indexOf("ChkBx") > 0 && inp.value != "" && inp.checked )
            {
                var chkbx = true;
                break;
            }
        }
    
    
        if ( oops == "" ) return true;
    	alert("ERROR(S):\n" + oops);    
        return false;
    }
    Can someone show me what I'm going wrong or if there's a better piece of code out there? When I leave the field blank I get the error code but when I enter a legit date with the proper format I still get the error...

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    The simplest way to validate a date in mm/dd/ccyy format in JavaScript is to load it into a date object and then test to make sure that the day, month and year in the date object are the same as those in the original string.

    Code:
    function isValidDate(dateString)
    {
        // First check for the pattern
        if(!/^\d{2}\/\d{2}\/\d{4}$/.test(dateString))
            return false;
    
        // Parse the date parts to integers
        var parts = dateString.split("/");
        var day = +parts[1];
        var month = +parts[0]-1;
        var year = +parts[2];
    
       if(year < 1000 || year > 3000) return false;
    
        var dt = new Date(year, month, day);
        if (dt.getDate() !== day || dt.getMonth() !== month || dt.getFullYear() !== year) return false;
        return true;
    }
    You could shorten the code slightly more by substituting a string.match for the regexp.test and string.split so as to both validate that the code contains the three numeric values and split them into an array in a single command.

    Are you sure that you are only passing the date without any leading or trailing spaces? Since you don't trim off any spaces a single space added to the date would cause it to fail validation.
    Last edited by felgall; 11-01-2012 at 10:25 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,037
    Thanks
    203
    Thanked 2,539 Times in 2,517 Posts
    This topic comes up quite often in the forum . Try using the search feature.

    Code:
    <script type = "text/javascript">
    
    function checkValidDate(yr,mmx,dd) {
    
    if (yr <1910 || yr >2012) {  // you may want to change 2012 to some other year!
    alert ("Year is out of range")
    return false;
    }
    
    mm = mmx-1;  // remember that in Javascript date objects the months are 0-11
    var nd = new Date();
    nd.setFullYear(yr,mm,dd);  // format YYYY,MM(0-11),DD
    
    var ndmm = nd.getMonth();
    if (ndmm != mm) {
    alert (dd + "/" + mmx + "/"   + yr  + " is an Invalid Date!");
    return false; 
    }
    else {
    alert (dd + "/" + mmx + "/" + yr  + " is a Valid Date");
    }
    }
    
    // USAGE
    checkValidDate(2011,2,31)  // 31st February 2011
    </script>
    Another way:-

    Code:
    <script type = "text/javascript">
    
     String.prototype.isValidDate = function(){
     var arrParts = this.split("/");
     var date1 = new Date(this.toString());
     dtReturn = (date1.getMonth()+1 == parseInt(arrParts[0],10) &&  date1.getDate() == parseInt(arrParts[1],10) &&  date1.getFullYear() == parseInt(arrParts[2],10) );
     return dtReturn;  // true or false
     }  
     
     var strDate1 = "01/31/2012";  // USA date format
     var strDate2 = "2/31/2012";
      
     alert(strDate1 + ": " + strDate1.isValidDate());
     alert(strDate2 + ": " + strDate2.isValidDate());
    
    </script>
    You need to make it clear to the user which format you want the date to be entered in. 3/5/2012 is 3rd May in UK and European format but is 5th March in USA format. Both are of course valid dates. You can also use a date picker or dropdowns.

    Quizmaster: What relation was King Edward VIII to the Queen?
    Contestant: Husband.
    Last edited by Philip M; 11-02-2012 at 09:06 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    hardhitter06 (11-27-2012)

  • #4
    New Coder
    Join Date
    Jun 2009
    Posts
    95
    Thanks
    15
    Thanked 0 Times in 0 Posts
    I definately need MM/DD/YYYY and I have that format written on form.

    Will both of these accomplish that, I am going to give them a try in a moment. Thank you for the responses.

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,037
    Thanks
    203
    Thanked 2,539 Times in 2,517 Posts
    Quote Originally Posted by hardhitter06 View Post
    I definately need MM/DD/YYYY and I have that format written on form.

    Will both of these accomplish that, I am going to give them a try in a moment. Thank you for the responses.
    Well, try them! But you can easily alter the date format. Another way to simplify date entry is to use three separate textboxes for MM, DD and YYYY.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #6
    New Coder
    Join Date
    Jun 2009
    Posts
    95
    Thanks
    15
    Thanked 0 Times in 0 Posts
    Neither are working or maybe I'm missing something with the space thing but I really don't know much.

    I use forums and google searches to find code and i'm usually good enough to tweak it to what i need but I'm really struggling with this.

    All I can tell you is I have an effective date field and it needs to be MM/DD/YYYY and I had this code which made sure it was in the right format:

    Code:
    var datechk = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/
    function dateCheck( fld )
    {
       var effectivedate = trim( fld );
       fld.value = effectivedate;
       return datechk.test(effectivedate);
    }
    (I have this commented out so it's not being used)

    But nothing to make sure it was a valid date.

    Should mention I tried both your pieces of code and even with a valid date I'm getting an error so again it might be a space thing...i really couldnt tell you...thanks guys

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,037
    Thanks
    203
    Thanked 2,539 Times in 2,517 Posts
    Quote Originally Posted by hardhitter06 View Post
    Neither are working
    They work for me!

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    New Coder
    Join Date
    Jun 2009
    Posts
    95
    Thanks
    15
    Thanked 0 Times in 0 Posts
    haha well I must be missing something then

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,037
    Thanks
    203
    Thanked 2,539 Times in 2,517 Posts
    Why do you say tha the scripts do not work? If you copy them into your browser and run them you will see that they do. Is the problem that you are passing the dates to the script in the wrong format?

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #10
    New Coder
    Join Date
    Jun 2009
    Posts
    95
    Thanks
    15
    Thanked 0 Times in 0 Posts
    I very well could be.

    When I use your code:

    Code:
    <script type = "text/javascript">
    
     String.prototype.isValidDate = function(){
     var arrParts = this.split("/");
     var date1 = new Date(this.toString());
     dtReturn = (date1.getMonth()+1 == parseInt(arrParts[0],10) &&  date1.getDate() == parseInt(arrParts[1],10) &&  date1.getFullYear() == parseInt(arrParts[2],10) );
     return dtReturn;  // true or false
     }  
     
     var strDate1 = "01/31/2012";  // USA date format
     var strDate2 = "2/31/2012";
      
     alert(strDate1 + ": " + strDate1.isValidDate());
     alert(strDate2 + ": " + strDate2.isValidDate());
    
    </script>
    Read more at http://www.codingforums.com/showthread.php?p=1287633#sMCWGL9tgxfdK7AE.99
    As soon as i open the form a message box opens saying those two dates you listed (01.31.12 and 2.31.12 are true.

    Why is that?

    BTW this is an html form...I don't know if that makes a difference.
    Last edited by hardhitter06; 11-02-2012 at 08:49 PM.

  • #11
    New Coder
    Join Date
    Jun 2009
    Posts
    95
    Thanks
    15
    Thanked 0 Times in 0 Posts
    I am now trying this:

    Code:
    function isValidDate(dateString) { 
    if(!/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/.test(dateString)) 
    return false; 
    
    var parts = dateString.split("/"); 
    var day = +parts[1]; 
    var month = +parts[0]-1; var year = +parts[2]; 
    
    if(year < 1000 || year > 3000) 
    return false; 
    
    var dt = new Date(year, month, day); 
    if (dt.getDate() !== day || dt.getMonth() !== month || dt.getFullYear() !== year) return false; 
    return true; }
    Followed by this:

    Code:
    function validateForm( frm )
    {
    	var oops = "";
    	var apptype = getRBValue( frm.elements["MoveType."] );
        if ( apptype == null )
            oops += "You must check Temporary or Permanent.\n";
    	var apptype = getRBValue( frm.elements["ResSummer."] );
        if ( apptype == null )
            oops += "You must check Yes or No for residential summer student.\n";
        if ( trim( frm.elements["FirstName."] ).length  < 2 )
            oops += "You must enter your First name.\n";
        if ( trim( frm.elements["LastName."] ).length  < 2 )
            oops += "You must enter your Last name.\n";
        if ( ! emailCheck( frm.elements["Email."] ) )
            oops += "That does not appear to be a valid Email Address.\n";
    	if (trim( frm.elements["Box."] ).length  < 1 || trim( frm.elements["Box."] ).length > 4)
            oops += "You must enter a Box# (Max 4 digits).\n";
        if ( ! isValidDate( frm.elements["EffectiveDate."] ) )
            oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";
    	if ( trim( frm.elements["StreetAddress."] ).length  < 5 )
            oops += "You must enter your Street Address.\n";
    	if ( trim( frm.elements["City."] ).length  < 4 )
            oops += "You must enter your City.\n";
        if ( trim( frm.elements["State."] ).length  < 1 )
            oops += "You must enter your State.\n";
    	if ( ! zipCheck( frm.elements["Zip."] ) )
            oops += "You must enter a 5 digit Zip Code.\n";
        // additional building and room are not validated, but they are are trimmed and upper cased
        trim(frm.Apt);
    	
        
        var inps = frm.elements;
        var chkbx = false;
        for ( var i = 0; i < inps.length; ++i )
        {
            var inp = inps[i];
            if ( inp.name.indexOf("ChkBx") > 0 && inp.value != "" && inp.checked )
            {
                var chkbx = true;
                break;
            }
        }
    
    
        if ( oops == "" ) return true;
    	alert("ERROR(S):\n" + oops);    
        return false;
    }
    After the rest of my functions....still doesn't work with a legit date...

  • #12
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Philip M View Post
    var nd = new Date();
    nd.setFullYear(yr,mm,dd); // format YYYY,MM(0-11),DD
    Surely that can be shortened to:

    Code:
    var nd = new Date(yr,mm,dd);
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #13
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,037
    Thanks
    203
    Thanked 2,539 Times in 2,517 Posts
    Quote Originally Posted by felgall View Post
    Surely that can be shortened to:

    Code:
    var nd = new Date(yr,mm,dd);
    Yes, well spotted!

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #14
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,037
    Thanks
    203
    Thanked 2,539 Times in 2,517 Posts
    As soon as i open the form a message box opens saying those two dates you listed (01.31.12 and 2.31.12) are true.
    The code is

    var strDate1 = "01/31/2012"; // USA date format
    var strDate2 = "2/31/2012";

    You must pass the date in the correct format.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #15
    New Coder
    Join Date
    Jun 2009
    Posts
    95
    Thanks
    15
    Thanked 0 Times in 0 Posts
    Do I need to mention my date field (EffectiveDate) someone in this code so it knows where to pull the date from?

    Aside from that question, is this code set up to validate the date in MM/DD/YYYY format?

    Code:
    function checkValidDate(yr,mmx,dd)
    {
    mm = mmx-1; // remember that in Javascript date objects the months are 0-11 
    var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD 
    
    var ndmm = nd.getMonth();
    if (ndmm != mm) 
    { 
    alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!"); return false; 
    } 
    else 
    { 
    alert (dd + "/" + mmx + "/" + yr + " is an Valid Date!"); } 
    }

    The two lines in green are the same so how does that work?

    And I have this piece of code in my function to validate the form:

    Code:
        if ( ! checkValidDate( frm.elements["EffectiveDate."] ) )
            oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";
    So do I even need an alert in the function above?

    Again I am a beginner with this type of stuff so I'm trying to figure it out. I appreciate your guys patience with me...I know sometimes that isn't easy.
    Last edited by hardhitter06; 11-05-2012 at 03:40 PM.


  •  
    Page 1 of 3 123 LastLast

    Posting Permissions

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