JavaScript Date Check Function

Can anyone explain how the foll JS function checks the date, which should be in the form mm / dd / yyyy.

<script type="text/javascript"> function checkdate(input){ var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity var returnval=false if (!validformat.test(input.value)) alert("Invalid Date Format. Please correct and submit again.") else{ //Detailed check for valid date ranges var monthfield=input.value.split("/")[0] var dayfield=input.value.split("/")[1] var yearfield=input.value.split("/")[2] var dayobj = new Date(yearfield, monthfield-1, dayfield) if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield)) alert("Invalid Day, Month, or Year range detected. Please correct and submit again.") else returnval=true } if (returnval==false) input.select() return returnval } </script> 
+4
source share
1 answer

The first part uses a regular expression to check if the value is in the required format mm/dd/yyyy . This ensures that the check fails if it is not a line / with numbers 2, 2 and 4, respectively.

The second part creates a date object using the individual values dd , mm and yyyy and checks the properties of the created object with the original input values. This is to ensure that the check is not performed for values ​​such as 02/31/2015

if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))

The above statement must ensure that the created object reflects the same values ​​that were used to create it. Also note that the month index starts at 0 , hence -1 at the time of creation and +1 at the time of verification.

+5
source

All Articles