Here explained how one can validate date without using any Custom Validator or Regular Expression using JavaScript
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.
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
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;
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]) {
//
alert("Valid Date");
}
else {
alert("InValid Date");
txt.value = '';
return;
}
}
else if
(val.length < 10) {
}
}
<asp:TextBox ID="txtLetterDate" CssClass="TextBox" runat="server" MaxLength="10"
onkeyup = "ValidateDate(this, event.keyCode)" onkeydown = "return DateFormat(this, event.keyCode)" Height="24px"></asp:TextBox>