JS validates date format

I have a text box in which the user enters a date-time in the format: dd/mm/YYYY hh:ii . I want to check if this is a valid date using javascript. That should include February 29th and all. How can i do this? Regular expression will not be performed due to special months.

+6
source share
3 answers

see http://internotredici.com/article/checkdateinjavascript/ for a useful time-checking article - exactly what you want!

Below is the full article

Check date in javascript An article published in the Scripts section on January 31, 2006. Programmers very often need to check the information inserted into forms, and it is useful to use javascript to check their correctness. This guide explains how to use javascript to check if the date is valid or not. Dates in forms are inserted in two different ways: the first uses a text field where user type data follows different templates (in this lesson, we assume that the dates are in the format dd-mm-yyyy); the second uses drop-down menus instead. The first solution is easier to implement, but it is subject to more user errors (for example, inserting invalid characters or more frequent input dates in a format different from what was planned). Suppose now that we have the following text box into which we want to insert a date in the format dd-mm-yyyy:

 <form id="test_form" action="get" method="/checkdatejavascript" onsubmit="return(check_form(this)); return false;"> <input type="text" name="datefield" id="datefield" /> </form> 

To check the correctness of the entered data, we will use the check_form function:

 function check_form() { // Regular expression used to check if date is in correct format var pattern = new RegExp([0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2}); if(document.getElementById('datefield').value.match(pattern)) { var date_array = document.getElementById('datefield') .value.split('-'); var day = date_array[0]; // Attention! Javascript consider months in the range 0 - 11 var month = date_array[1] - 1; var year = date_array[2]; // This instruction will create a date object source_date = new Date(year,month,day); if(year != source_date.getFullYear()) { alert('Year is not valid!'); return false; } if(month != source_date.getMonth()) { alert('Month is not valid!'); return false; } if(day != source_date.getDate()) { alert('Day is not valid!'); return false; } } else { alert('Date format is not valid!'); return false; } return true; 

} As we can see, the regular expression shown in blue is used to control if the serial date matches or does not match the default format. If the template is valid, then the function proceeds to the next step, otherwise the error message is raised. The abd form is not submitted (the regular expression ensures that the date cannot be empty). To check the date, we will use the Date object offered by javascript. (check the code shown in red). The algorithm is pretty simple. Using the data entered by the user, we will create a Date object and using the getFullYear, getMonth and getDate methods we will create three values ​​representing the year, month and day, respectively, associated with it. If these values ​​are equal to the values ​​entered by the user, then the date is correct. Now consider the following examples:

The user inserts the line 09-01-1976 into the text field. Date object created from the line - 09-01-1976 Date is valid

The user inserts the line 31-02-2006 into the text field. Date object created from the line, 03-03-2006 Date is invalid

The program had to pay special attention (check the code marked in green), since javascript processes dates, because months are counted in the range from 0 to 11, assuming that o is January and 11 is December. In the case where the drop-down menus are used to insert dates, the controls are simpler because the regular expression does not require checking the date format:
  <form id="test_form" action="get" method="/checkdatejavascript" onsubmit="return(check_form(this)); return false;"> <select name="dateday" id="dateday"> <option value="1">1</option> […] </select> <select name="datemonth" id="datemonth"> <option value="0">January</option> […] </select> <select name="dateyear" id="dateyear"> <option value="2006">2006</option> […] </select> </form> 

The javascript function that will control the correctness of the date will be

  function check_form() { var day = document.getElementById('dateday').value; var month = document.getElementById('datemonth').value; var year = document.getElementById('dateyear').value; // This instruction will create a date object source_date = new Date(year,month,day); if(year != source_date.getFullYear()) { alert('Year is not valid!'); return false; } if(month != source_date.getMonth()) { alert('Month is not valid!'); return false; } if(day != source_date.getDate()) { alert('Day is not valid!'); return false; } return true; } 

Update: I updated the code because there was a problem with the regex. Thanks to Alex for the tip.

+3
source

If using the moment.js parameter is ok, you can check http://momentjs.com/docs/#/parsing/string-format/ for date and time parsing utilities. For instance:

 moment("29/02/2014 11:45", "DD/MM/YYYY hh:mm", true).isValid() 
+2
source

If you do not want to use other external libraries, you can use the following function:

 var validateDate = function(dateTime){ var f_date = dateTime.split(" ")[0].split("/").reverse().join("/"); var time = dateTime.split(" ")[1]; var date = dateTime.split(" ")[0].split("/").map(function(c, i, a){ return parseInt(c); }); var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]; if ( (!(date[2] % 4) && date[2] % 100) || !(date[2] % 400)) { console.log("inside"); daysInMonth[1] = 29; } if(date[0] > 0 && (date[0] <= daysInMonth[(date[1]-1)]) && date[1] > 0 && date[1] <= 12){ return new Date(f_date + " " + time) != "Invalid Date"; } return false; } 

It will also take care of leap year variations. This function will only work if the input is in the format dd/mm/YYYY hh:ii . You can try some input examples, for example:

 validateDate("29/2/2000 12:30"); // Should return true validateDate("29/2/2001 12:30"); // Should return false validateDate("32/8/2000 12:30"); // Should return false validateDate("30/11/2000 12:30"); // Should return true validateDate("31/4/2000 12:30"); // Should return false validateDate("15/7/2000 12:77"); // Should return false 
+1
source

All Articles