Here I am explaining Validation of date using JavaScript. Along with validation it will also enforce Date Format restrictions dynamically as the user types the date in the textbox.
The whole idea of the tutorial is to dynamically validate the data and display the results when the user is typing the same. The advantage of this approach is that it allows the user to correct its mistake first and the move to the next item
The article will cover the following aspects of data validation
1. Enforcing date format dynamically i.e dd/mm/yyyy
2. Validating date dynamically on key events.
3. Validating whether the date entered is within the valid range
4. Validating Birthdates
Validation and Date format Enforcement
The DateFormat function enforces the following conditions
1. The characters entered should be numeric
2. Automatically appends slashes as the user types it
It enforces numeric character check based on the keyboard key values thus simply do not allow the user to enter any character except number.
For more information on this validation refer the article TextBox Validation using JavaScript
The next function ValidateDate as the name suggest simply validates the date. Using the JavaScript date functions and notifies the user whether the data is valid or not.
The compete script code for the two functions is given below
<script type = "text/javascript">
var isShift=false;
var seperator = "/";
function DateFormat(txt , keyCode)
{
if(keyCode==16)
isShift = true;
//Validate that its Numeric
if(((keyCode >= 48 && keyCode <= 57) || keyCode == 8 ||
keyCode <= 37 || keyCode <= 39 ||
(keyCode >= 96 && keyCode <= 105)) && isShift == false)
{
if ((txt.value.length == 2 || txt.value.length==5) && keyCode != 8)
{
txt.value += seperator;
}
return true;
}
else
{
return false;
}
}
function ValidateDate(txt, keyCode)
{
if(keyCode==16)
isShift = false;
var val=txt.value;
var lblmesg = document.getElementById("<%=lblMesg.ClientID%>") ;
if(val.length == 10)
{
var splits = val.split("/");
var dt = new Date(splits[1] + "/" + splits[0] + "/" + splits[2]);
//Validation for Dates
if(dt.getDate()==splits[0] && dt.getMonth()+1==splits[1]
&& dt.getFullYear()==splits[2])
{
lblmesg.style.color="green";
lblmesg.innerHTML = "Valid Date";
}
else
{
lblmesg.style.color="red";
lblmesg.innerHTML = "Invalid Date";
return;
}
//Range Validation
if(txt.id.indexOf("txtRange") != -1)
RangeValidation(dt);
//BirthDate Validation
if(txt.id.indexOf("txtBirthDate") != -1)
BirthDateValidation(dt)
}
else if(val.length < 10)
{
lblmesg.style.color="blue";
lblmesg.innerHTML =
"Required dd/mm/yy format. Slashes will come up automatically.";
}
}
</script>
You will notice that I am calling two more functions
1. RangeValidation
2. BirthDateValidation
RangeValidation
RangeValidation function validates that the date falls within a valid range for here I have used the range 01/01/1900 to 31/12/2099 If the date is not within the range it is termed as invalid.
Refer the script below
<script type = "text/javascript">
function RangeValidation(dt)
{
var startrange = new Date(Date.parse("01/01/1900"));
var endrange = new Date(Date.parse("12/31/2099"));
var lblmesg = document.getElementById("<%=lblMesg.ClientID%>") ;
if (dt<startrange || dt>endrange)
{
lblmesg.style.color="red";
lblmesg.innerHTML = "Date should be between 01/01/1900 and 31/12/2099";
}
}
</script>
BirthDateValidation
BirthDateValidation function validates the BirthDate based on two conditions
1. The date should be less that equal to the current date
2. The date should be greater that the difference between the current date and the date 100 years back.
<script type = "text/javascript">
function BirthDateValidation(dt)
{
var dtToday = new Date();
var pastDate = new Date(Date.parse(dtToday.getMonth()+"/"+
dtToday.getDate()+"/"+parseInt(dtToday.getFullYear()-100)));
var lblmesg = document.getElementById("<%=lblMesg.ClientID%>");
if (dt<pastDate || dt>=dtToday)
{
lblmesg.style.color="red";
lblmesg.innerHTML = "Invalid BirthDate";
}
else
{
lblmesg.style.color="green";
lblmesg.innerHTML = "Valid BirthDate";
}
}
</script>
The script will be called on TextBox keyup and keydown events in the following way
<asp:TextBox ID="txtValidate" runat="server" MaxLength = "10"
onkeyup = "ValidateDate(this, event.keyCode)"
onkeydown = "return DateFormat(this, event.keyCode)"></asp:TextBox>
You can try out the demo script here.
The JavaScript is tested in the following browsers
1. Internet Explorer 7
2. Firefox 3
3. Google Chrome
The source code is available to download
DateValidations.zip (2.75 kb)