472,364 Members | 1,585 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,364 software developers and data experts.

Date validation using onkeydown in Javascript and ASP

Rob
I have a date text box (input type = text) in an ASP.NET/Javascript
environment. I wanted to force the users to enter dates in a
"__/__/____", "dd/mm/yyyy" or similar format. The textbox needs to
support normal copy/paste/delete format. There wasn't much on Google
to help so (after a bit of toil) though I'd post my suggested solution
here. No guarantees I'm afraid; just hope it helps somebody out there.

Rob

Here's the ASP source code:

<%@ Page Language="vb" AutoEventWireup="false"
Codebehind="WebForm2.aspx.vb" Inherits="WebApplication1.WebForm2"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script language="Javascript" src="DateMask.js"></script>
</head>
<body>
<form id="frmMain">
<b>Date TextBox</b><p></p>
Enter Date:
<input type="text" name="txtDate" id="txtDate" size="10"
maxlength="10" onkeydown="dateOnKeyDown()"
onpaste="dateOnPaste(this)" value="__/__/____">
<p></p>
</form>
</body>
</html>

And the contents of DateMask.js:

function dateOnKeyDown() {
/* Purpose : Formats date text field so it adheres to
* the dd/mm/yyyy format
*
* Effects : Sets the value of the text field
*
* Inputs : None
*
* Returns : None
*/

var DATE_DIVIDER = "/";
var SPACE_CHARACTER = "_";

var objTextBox = window.event.srcElement;
var iKeyCode = window.event.keyCode;
var bSelectedText = false;

// Exit if field is read-only
if (window.event.srcElement.readOnly) return;

// Allow key presses of <cursor arrow> or <Home> or <End>
if ((iKeyCode > 36 && iKeyCode < 41) || (iKeyCode > 34 && iKeyCode <
37)) {
return 1;
}

// Allow <Ctrl+C>, <Ctrl+V>, <Ctrl+X> and <Ctrl+Z>
if (window.event.ctrlKey && (iKeyCode == 67 || iKeyCode == 86 ||
iKeyCode == 88 || iKeyCode == 90)) {
return 1;
}

// Get the position of the cursor
var iCaretPosition = getCaretPosition(objTextBox);

// Get the selected text
var objSelectedText = document.selection.createRange();

// Determine if some text has been selected
if (objSelectedText.parentElement() == objTextBox &&
objSelectedText.text.length > 0)
{
bSelectedText = true;
}

// Get the element next to the cursor (to be used later)
var sFirstElement = objTextBox.value.substring(iCaretPosition,
iCaretPosition-1);

// Do not enter number if there's no space for it
if ((sFirstElement != SPACE_CHARACTER) && !(iKeyCode == 8 || iKeyCode
== 46) && objSelectedText.text == 0) {
return 0;
}

// If key pressed is <0-9>
if ((iKeyCode > 47 && iKeyCode < 58) ||
(iKeyCode > 95 && iKeyCode < 106)) {
if (iKeyCode > 95) iKeyCode -= (95-47);

// Do not update text/move cursor if it is at the end of the textbox
if (iCaretPosition != 11) {

// Only write the character if it's filling an empty gap
// ie don't overwrite existing number or '/' characters
var sNextElement = objTextBox.value.substring(iCaretPosition-1,
iCaretPosition);

if (!bSelectedText && sNextElement == SPACE_CHARACTER) {
// Get the text before the cursor
var sElement1 = objTextBox.value.substring(0, iCaretPosition-1);
// Get the text after the cursor
var sElement2 = objTextBox.value.substring(iCaretPosition +
objSelectedText.text.length, objTextBox.value.length);
// Append the new character
sElement1 += String.fromCharCode(iKeyCode);
// Append the text from after the cursor
sElement1 += sElement2;
objTextBox.value = sElement1;

// Move the cursor position on one for "/" charcters
switch (iCaretPosition) {
case 2:
case 5:
iCaretPosition = iCaretPosition+1;
default:
}
}

// Handle selected text
if (bSelectedText) {

// Get the text before the selected text
var sElement1 = objTextBox.value.substring(0, iCaretPosition-1);

// We need to keep "/" characters
if (sFirstElement == DATE_DIVIDER) {
sElement1 += DATE_DIVIDER;
}

// Append the new character
sElement1 += String.fromCharCode(iKeyCode);

// Replace the remaining selected text with blank spaces
for (var i=1; i<objSelectedText.text.length; i++) {
var sDeletedChar = objSelectedText.text.substring(i, i+1);
if (sDeletedChar == DATE_DIVIDER) {
// Keep the slash characters
sElement1 += DATE_DIVIDER;
} else {
// Do not insert extra space if the first selected character is
a "/"
if (!(i==1 && sFirstElement == DATE_DIVIDER)) {
// Replace numbers with a space
sElement1 += SPACE_CHARACTER;
}
}
}

// Get the text after the selected text and append
var sElement2 = objTextBox.value.substring(iCaretPosition +
objSelectedText.text.length-1, objTextBox.value.length);
sElement1 += sElement2;
objTextBox.value = sElement1;
}

// Put the cursor in the correct position
objSelectedRange = objTextBox.createTextRange();

// Move cursor on 1 if the first selected character is a "/"
if (bSelectedText && sFirstElement == DATE_DIVIDER) iCaretPosition
= iCaretPosition+1;
objSelectedRange.move("character", iCaretPosition)
objSelectedRange.select();

}
} // End if key pressed is <0-9>

// If key pressed is <Del>
if (iKeyCode == 8 || iKeyCode == 46) {

// Handle selected text
if (bSelectedText) {

// Get the text before the selected text
var sElement1 = objTextBox.value.substring(0, iCaretPosition-1);

// We need to keep "/" characters
if (sFirstElement == DATE_DIVIDER) {
sElement1 += DATE_DIVIDER;
}

// Append the new character
sElement1 += SPACE_CHARACTER;

// Replace the remaining selected text with blank spaces
for (var i=1; i<objSelectedText.text.length; i++) {
var sDeletedChar = objSelectedText.text.substring(i, i+1);
if (sDeletedChar == DATE_DIVIDER) {
// Keep the slash characters
sElement1 += DATE_DIVIDER;
} else {
// Do not insert extra space if the first selected character is a
"/"
if (!(i==1 && sFirstElement == DATE_DIVIDER)) {
// Replace numbers with a space
sElement1 += SPACE_CHARACTER;
}
}
}

// Get the text after the selected text and append
var sElement2 = objTextBox.value.substring(iCaretPosition +
objSelectedText.text.length-1, objTextBox.value.length);
sElement1 += sElement2;
objTextBox.value = sElement1;

iCaretPosition = iCaretPosition+1;

} else {
// We need to delete character by character
if (iCaretPosition != 11 || iKeyCode != 46) {

if (iKeyCode == 46) iCaretPosition = iCaretPosition+1;

if (iCaretPosition != 1 && iCaretPosition != 4 && iCaretPosition
!= 7){
var sElement1 = objTextBox.value.substring(0, iCaretPosition-2);
var sElement2 = objTextBox.value.substring(iCaretPosition-1,
objTextBox.value.length);
sElement1 += SPACE_CHARACTER;
sElement1 += sElement2;
objTextBox.value = sElement1;
}
}
}

// Put the cursor in the correct position
objRange = objTextBox.createTextRange();
// Move cursor on 1 if the first selected character is a "/"
if (bSelectedText && sFirstElement == DATE_DIVIDER) iCaretPosition =
iCaretPosition+1;
objRange.move("character", iCaretPosition - 2)
objRange.select();

} // End if key pressed is <Del>

// If key pressed is <Tab>
if (iKeyCode != 9) {
event.returnValue = false;
}
}
function getCaretPosition(objTextBox){
/* Purpose : Returns the caret position of the cursor
* in the text box
*
* Effects : None
*
* Inputs : objTextBox - a text box
*
* Returns : Integer indicating the caret position
* in the text box
*/

var i = objTextBox.value.length+1;

if (objTextBox.createTextRange){
objCaret = document.selection.createRange().duplicate();
while (objCaret.parentElement()==objTextBox &&
objCaret.move("character",1)==1) --i;
}

return i;
}

function dateOnPaste(objTextBox) {
/* Purpose : Handles paste event
*
* Effects : Copies the clipboard value to the text field
*
* Inputs : None
*
* Returns : None
*/

var sClipboard = window.clipboardData.getData('Text');

// Validate that the pasted text is in nn/nn/nnnn format
if (sClipboard.match(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/)) {
objTextBox.value = sClipboard;
} else {
// Do not allow paste
window.event.returnValue = 0;
}
}
Jul 23 '05 #1
1 13859
JRS: In article <35**************************@posting.google.com >,
dated Mon, 15 Nov 2004 06:25:53, seen in news:comp.lang.javascript, Rob
<ro******@hotmail.com> posted :
Lines: 290 I have a date text box (input type = text) in an ASP.NET/Javascript
environment. I wanted to force the users to enter dates in a
"__/__/____", "dd/mm/yyyy" or similar format. The textbox needs to
support normal copy/paste/delete format. There wasn't much on Google
to help so (after a bit of toil) though I'd post my suggested solution
here. No guarantees I'm afraid; just hope it helps somebody out there.
Those paid by the yard, perhaps.

ISTM better to allow anything to be put in the box and to check it for
being the right format, /^\d\d\/\d\d\/\d\d\d\d$/, when appropriate. Why
not do a proper check of the date value, including rejection of day too
big for month and test within plausible year range? It takes rather
little code - see newsgroup FAQ & sig below, then js-date4.htm.

You have apparently allowed your posting agent to wrap code lines. That
is bad; code for News should be written not to exceed about 72
chars/line, with line-breaks and indentation added judiciously.
Here's the ASP source code:

<%@ Page Language="vb" AutoEventWireup="false"
Codebehind="WebForm2.aspx.vb" Inherits="WebApplication1.WebForm2"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
if (sClipboard.match(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/)) {


For [0-9] write \d.
For dd/mm/yyyy, /^[0-3]\d\/[01]\d\/\d{4}$/ would, for example, reject
12/25/2004; but if a proper check is done there is no need to RegExp
specific digits.
BTW, your
// Allow key presses of <cursor arrow> or <Home> or <End>
if ((iKeyCode > 36 && iKeyCode < 41) || (iKeyCode > 34 && iKeyCode <
37))

seems odd; does it mean 36 36 37 38 39 40 ?
Also, it's trivial to be more liberal with the separator; some prefer
space, dot, or minus. /^\d\d(\D)\d\d\1\d\d\d\d$/ should allow any
repeated separator.
--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Richard Hollenbeck | last post by:
I'm trying to write some code that will convert any of the most popular standard date formats twice in to something like "dd Mmm yyyy" (i.e. 08 Jan 1908) and compare the first with the second and...
3
by: arc | last post by:
I have a server object that performs zipcode validation based on zipcode entered in the web form. Ideally this should work as follows: Once the zip code is entered in the edit box it should...
30
by: Dr John Stockton | last post by:
It has appeared that ancient sources give a method for Numeric Date Validation that involves numerous tests to determine month length; versions are often posted by incomers here. That sort of code...
4
by: peashoe | last post by:
I have an asp page that uses a calendar.js (pop-up) file to add an exact date format in the text field (txtDDate). My problem is I need some javascript that sets an alert that does not allow them...
8
by: dlx_son | last post by:
Here is the code so far <form name="thisform"> <h3>Enter time to add to or subtract from:</h3> (If not entered, current time will be used)<br> Day: <input name="d1" alt="Day of month"...
23
by: Ash | last post by:
Hi everyone, This problem has been puzzling me for a fair time now, and has severely frustrated me!! Perhaps I'm just not getting the syntax right, but the problem is rather simple... Take a...
7
by: Paul | last post by:
Hi, I have a form where a user is required to enter a start date and an end date. Both are required and must between a specific date range (e.g. 01/01/1900 and 01/01/2099) and the end date...
3
by: pmarisole | last post by:
The following javascript code gives me the date validation that I need except after the correct date is entered into the field, it puts the date in the wrong format EXAMPLE: User enters...
17
by: Petyr David | last post by:
Just looking for the simplest. right now my perl script returns an error messge to the user if the date string is invalid. would like to do this before accessing the server. TX
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.