0

I am trying to write a javascript date format validation without using regular expression. When I entered the date 26/02/2013 I am having an alert value of Wed Sep 2 2093 and the error message the date is not a valid format

Any help will be appreciate

    function CheckDateFormat(StartDateform)     

    {   
            var StartDateform= document.getElementById('tblTarget').rows[1].cells[StartDate].getElementsByTagName('input')[0].value;        
            spl = StartDateform.split("/"); 


            var testDate=new Date(spl[2],spl[0]-1,spl[1]);              

            year= testDate.getFullYear();                   
            month = testDate.getMonth()+1;                  
            day= testDate.getDate();

            alert ("the date value is "+ " "+ testDate);

        if (day!==spl[1] || month!==spl[0] || year!==spl[2])                    
        {
            alert ("the date value is "+ " "+ testDate);
            alert(StartDateform + " " + "Is an Invalid Date. Please use the format 'MM/DD/YYYY'");
            return false;
        }


        return true;                        
    }                   

    function Submit() 
    {
        if(CheckDateFormat())
        {
        $('button_submit').click(); 
        alert('New rate submitted');
        }
    }
flup
  • 26,937
  • 7
  • 52
  • 74
  • 1
    Why without a regular expression? Regular expressions are great for this kind of thing. – rjmunro Jul 17 '13 at 09:05
  • Just for your information, there exist some really mature JS libraries which do a great job on parsing dates, like **http://momentjs.com/**. – thmshd Jul 17 '13 at 09:07
  • 1
    @rjmunro regexp is bad for validating dates, because you will need to validate a lot of invalid dates as well, f.ex leap years and other irregularities in the calendar. – David Hellsing Jul 17 '13 at 09:07
  • why are you passing `StartDateform` as Parameter whereas you have not use that and not passed when calling function.. – Sachin Jul 17 '13 at 09:08
  • Just parse it...! and cross fingers – Adrian Salazar Jul 17 '13 at 09:14
  • A previous post might prove to be useful http://stackoverflow.com/questions/7042042/create-javascript-date-object-from-date-string – AurA Jul 17 '13 at 09:14
  • 26/02/2013 is not a valid MM/DD/YYYY format, your code is working. – rjmunro Jul 17 '13 at 09:19

1 Answers1

1

The Date constructor expects Y/M/D:

Date - Creates JavaScript Date instances which let you work with dates and times.

Syntax

new Date();
new Date(value);
new Date(dateString);
new Date(year, month, day [hour, minute, second, millisecond]);

If the date is 26/02/2013, you're feeding it with Y/D-1/M:

new Date(spl[2],spl[0]-1,spl[1]);

Substracting 1 from the day doesn't make any sense so I guess you've just messed the indexes.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360