Description:
In this article,
I will explain how to validate date using Jquery.
Javascript is a great way to validate date
input field before the users submit the data.
Here, I am
creating a function which accepts date value as input parameter and it will
check with the regular expression which is defined in the function.
This function
will split into three parts for date, month and year.
Now it will check
all validation for three parts. For example: Date should not be greater than 31
and Month should not be greater than 12 .
Also, it will
check the value is empty or not.
All kind of date
validation is checked in the following function.
Example Program:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnDateValidation').click(function () {
var dt = $('#txtDate').val();
return DateValidationFunc(dt);
});
});
</script>
<script type="text/javascript">
function DateValidationFunc(input) {
var dtFormat =
/^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;
if (dtFormat.test(input))
{
input = input.replace(/0*(\d*)/gi, "$1");
var dtArray =
input.split(/[\.|\/|-]/);
dtArray[1] = dtArray[1] - 1;
if (dtArray[2].length
< 4) {
dtArray[2] = (parseInt(dtArray[2]) < 50) ? 2000 + parseInt(dtArray[2]) :
1900 + parseInt(dtArray[2]);
}
var Dateval = new Date(dtArray[2],
dtArray[1], dtArray[0]);
if (Dateval.getDate() !=
dtArray[0] || Dateval.getMonth() != dtArray[1] || Dateval.getFullYear() !=
dtArray[2]) {
alert("Invalid
Date");
return false;
} else {
alert("Valid
date");
return true;
}
} else {
alert("Invalid
Date! Please Enter DD/MM/YYYY Format");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:Button ID="btnDateValidation" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
0 comments:
Post a Comment