Friday, 4 October 2013

JavaScript Date Validation.


Hi My dear Friends here I am going to explain how to validate the date whether the User entered the Correct Date or Not in the aspx page.


<script type="text/javascript">
function ValidateDate() {
var validformat = /^\d{2}\-\d{2}\-\d{4}$/; //Basic check for format validity
var txtDate = document.getElementById('Your TextBox Control Id.');
var returnval = false;

if (!validformat.test(txtDate.value))
alert("Invalid Date Format. Please correct and submit again.")
else { //Detailed check for valid date ranges
var monthfield = txtDate.value.split("-")[1]
var dayfield = txtDate.value.split("-")[0]
var yearfield = txtDate.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) {
txtDate.select()
}

return returnval;
}
</script>

Note:
Call the ValidateDate in the button click like OnClientClick="return ValidateDate()”

No comments:

Post a Comment