Introduction
I have been working for a project where users should add a lot of registers
with some date fields. I used a select date control but users were angry of
having to select year then month and finally day to get the date they want. I
was looking for a control like a masked Textbox for ASP .NET (I found some
examples for Windows form and another for ASP .NET but with a cost) So I
decided to make this user control to put it in all the pages I need.
What does the control is that only let the users type numbers so the control
will make a Date with them (mm/dd/yyyy, dd/mm/yyyy depends on Date local
configuration).
The user control have a Required Validator and a Custom Validator
These code are the most important piece of the control. First sentence let only type numbers and second once the Textbox lost focus format the value on it to have mm/dd/yyyy. If the user didn´t type 8 numbers it clear the Textbox.
'Add Event KeyPress to let type only numbers
txtCDate.Attributes.Add("onkeypress", "return CheckDate(event,'" & txtCDate.ClientID & "')")
'Add Event OnBlur to be sure that Typed numbers could be a Date 8 Characters and adds the /
'to get a Date 01/01/2006
txtCDate.Attributes.Add("onblur", "return ChangeDate(event,'" & txtCDate.ClientID & "')")
rfvDate.ErrorMessage = ReqErrorMessage
Last code add attributes to Textbox so we can have the Keypress and Onblur event firing the next functions in JavaScript
function CheckDate(e,Id)
{
if(e.keyCode < 48 || e.keyCode > 57)
{
return false;
}
else
{
return true;
}
}
function ChangeDate(e,txtId)
{
var txt = document.getElementById(txtId)
var Date = txt.value.toString();
var Date2 = Date;
if(Date.length == 8)
{
Date = Date2.charAt(0)+ Date2.charAt(1) + "/";
Date += Date2.charAt(2)+ Date2.charAt(3) + "/"
Date += Date2.charAt(4)+ Date2.charAt(5)+Date2.charAt(6)+ Date2.charAt(7);
}
else
Date = "";
txt.value = Date;
return false;
}
This is a simple code but it was useful for me and I think could be for someone else. I tried to have the CustomValidator working from the ascx if anyone can fix that don´t hesitate to do it and tell me what we can do for that. This is my firt article sorry for my english.
Graduated from Technological Institute of Hermosillo (my city) as Computer Systems Engineer. I have worked with three companies where I developed some desktop and web aapplications. I love programmning, playing the violin and being with my family.
I´m married with a beatiful daughter.