<!DOCTYPE html> <html> <head> </head> <body onload='document.getElementById("text1").focus()'> <div class="mail"> <h2>Input a valid date [MM-DD-YYYY format]</h2> <span id="form1"> <input type='text' name='text1' id='text1'/> <input type="submit" name="submit" value="Submit" onclick="validatedate()"/> </span> <p id="result"></p> </div> <script> function validatedate() { var dateformat = /^\d{2}\-\d{2}\-\d{4}$/; var datevalue = document.getElementById("text1").value; if (notEmpty (datevalue, "Please enter date in MM-DD-YYYY format")){ if(isAlphabet(datevalue, "Please enter date in MM-DD-YYYY format")){ if (datevalue.match(dateformat)) { document.getElementById("text1").focus(); var opera = datevalue.split('-'); if (opera.length > 1) { var mm = parseInt(opera[0]); var dd = parseInt(opera[1]); var yy = parseInt(opera[2]); var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31]; if (mm==1 || mm>2) { if (dd>ListofDays[mm-1]) { document.getElementById("result").innerHTML = "Invalid date. Please enter date in MM-DD-YYYY format"; document.getElementById("text1").focus(); return false; } } // Check for Leap Year (Febuary (02) MOnth) if (mm==2) { var lyear = false; if ( (!(yy % 4) && yy % 100) || !(yy % 400)) { lyear = true; } if ((lyear==false) && (dd>=29)) { document.getElementById("result").innerHTML = "Invalid date. Please enter date in MM-DD-YYYY format"; document.getElementById("text1").focus(); return false; } if ((lyear==true) && (dd>29)) { document.getElementById("result").innerHTML = "Invalid date. Please enter date in MM-DD-YYYY format"; document.getElementById("text1").focus(); return false; } } // Check for All Digits are zero if (mm==0 || dd==0 || yy == 0) { document.getElementById("result").innerHTML = "Please enter date in MM-DD-YYYY format"; document.getElementById("text1").focus(); return false; } document.getElementById("result").innerHTML = 'You have entered valid date. Its '+datevalue+' Thank you.'; document.getElementById("text1").focus(); return true; } else { document.getElementById("result").innerHTML = "Please enter date in MM-DD-YYYY format"; document.getElementById("text1").focus(); return false; } } else { document.getElementById("result").innerHTML = "Please enter date in MM-DD-YYYY format"; document.getElementById("text1").focus(); return false; } } } // Match the date format through regular expression } function notEmpty(elem, helperMsg){ if(elem.length == 0){ document.getElementById("result").innerHTML = "Invalid date. Please enter date in MM-DD-YYYY format"; document.getElementById("text1").focus(); // set the focus to this input return false; } return true; } function isAlphabet(elem, helperMsg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.match(alphaExp)){ document.getElementById("result").innerHTML = helperMsg; document.getElementById("text1").focus(); // set the focus to this input return false; }else{ return true; } } </script> </body> </html>
0 Comments