Solved

Problem validating values in two date fields in jsp and javascript

Posted on 2012-04-05
13
463 Views
Last Modified: 2012-06-16
I am struggling with a form in jsp, which contains two date input fields; the date fields are placed consecutively/adjacently on the form. It needs to validate the date entered in each field, and to re-format the date. If the value entered is invalid, I need to cursor to stay in the field until the user enters a valid date.

I use a javascipt function to perform the validation. To execute the javascript function, I use onBlur.

Here is the problem: when I enter an invalid value in either one of the fields, the cursor infinitely jumps between one date field and the other. Once in this state, the browser does not respond to the keyboard, and the user must kill it using Task Manager.

I tried onChange and so on, but to no avail. I also tried creating two different functions: one for each date field.

Below is the code I have:

// Javascript to check date input for format M/D/YY and converts to DD-MMM-YYYY.
// If user enters DD-MMM-YYYY, that's okay too.

monthno = "01,02,03,04,05,06,07,08,09,10,11,12".split(",");
monthabbr = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");
function generic_date_validator(theField, theErrorField)
{
	var errval = "";

	dPart = theField.value.split(/\W+/);
	if(dPart.length!=3)
	{
		return false;
	}

// Try date input for format dd-MMM-yyyy first.

	for(i=0;i<monthabbr.length;i++)
	{
		if(dPart[1].toLowerCase()==monthabbr[i].toLowerCase())
		{
			dPart[1]=i;
			break;
		}
	}

	if (i < 12)
	{
		nDate = new Date(dPart[2], dPart[1], dPart[0]);
		if (!(isNaN(nDate) || dPart[2]!=nDate.getFullYear() ||
			dPart[1]!=nDate.getMonth() || dPart[0]!=nDate.getDate()))
		{
			theField.value = nDate.getDate()+"-"+monthabbr[dPart[1]]+"-"+nDate.getFullYear();
			return true;
		} else {
			return false;
		}
	} else {

// If failed to match, try matching input using format M/D/YY next.

		for(i=0;i<monthno.length;i++)
		{
			if(dPart[0]==monthno[i] || ("0"+dPart[0])==monthno[i])
			{
				dPart[0]=i;
				break;
			}
		}

		nDate = new Date(dPart[2], dPart[0], dPart[1]);
		if (isNaN(nDate) || dPart[2]!=nDate.getYear() ||
			dPart[0]!=nDate.getMonth() || dPart[1]!=nDate.getDate())
		{
			return false;
		} else {
			if (dPart[2] <= 99) // only two-digit year entered, default century to 2000?
			{
				theField.value = nDate.getDate()+"-"+monthabbr[dPart[0]]+"-"+(2000 + nDate.getYear());
			} else {
				theField.value = nDate.getDate()+"-"+monthabbr[dPart[0]]+"-"+nDate.getFullYear();
			}
		return true;
		}
	}
}

function date_validator(theField)
{
	var datefield = theField;
	var errval = "";

	if (generic_date_validator(theField) == false)
	{
		errval = "Error: You must enter a date in the form of M/D/YY or DD-Mmm-YYYY.";
		document.getElementById("formerror").innerHTML = errval;
		datefield.select();
		datefield.focus();
		return false;
	}
	else
	{
		errval = "";
		document.getElementById("formerror").innerHTML = errval;
		return true;
	}
}

Open in new window

0
Comment
Question by:bluegreen288
  • 8
  • 5
13 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37815330
It is a blur plus focus that is the baddie.
Never focus in a function called on blur

You can change your code to

var datefield; // now global
function date_validator(theField)
{
  datefield = theField;
  var errval = "";

  if (generic_date_validator(theField) == false)
  {
    errval = "Error: You must enter a date in the form of M/D/YY or DD-Mmm-YYYY.";
    document.getElementById("formerror").innerHTML = errval;
    setTimeout(function() {
      datefield.select();
      datefield.focus();
    },10); // focus after 10 milliseconds
    return false;
  }

Open in new window

0
 

Author Comment

by:bluegreen288
ID: 37816383
It works partially. It slowed down the switching between date fields. This way, I am able to go in and press buttons on the screen, one of which is a reset button.

Thanks.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37816593
What does partially mean. Do you have a URL?
0
Manage your data center from practically anywhere

The KN8164V features HD resolution of 1920 x 1200, FIPS 140-2 with level 1 security standards and virtual media transmissions at twice the speed. Built for reliability, the KN series provides local console and remote over IP access, ensuring 24/7 availability to all servers.

 

Author Comment

by:bluegreen288
ID: 37823647
Snapshot of begin and end date issueBy partially, I meant the mouse cursor still alternates between the two date fields. I cannot provide you a URL. If I time it right, I can click on the Find button to stop the alternating.

 

I hope this helps.

Thanks.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37823755
I'll take a look
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 37823974
Try this DEMO

// Javascript to check date input for format M/D/YY and converts to DD-MMM-YYYY.
// If user enters DD-MMM-YYYY, that's okay too.

monthno = "01,02,03,04,05,06,07,08,09,10,11,12".split(",");
monthabbr = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");
function generic_date_validator(theField) {
  var errval = "";

  dPart = theField.value.split(/\W+/);
  if(dPart.length!=3) {
    return false;
  }

// Try date input for format dd-MMM-yyyy first.

  for(var mn=dPart[1].toLowerCase(),i=0;i<monthabbr.length;i++) {
    if (mn==monthabbr[i].toLowerCase())     {
      dPart[1]=i;
      break;
    }
  }

  if (i < 12) {
    nDate = new Date(dPart[2], dPart[1], dPart[0]);
    if (isNaN(nDate) ||
       dPart[2]!=nDate.getFullYear() ||
       dPart[1]!=nDate.getMonth() ||
       dPart[0]!=nDate.getDate()) {
      return false;    
    }
    theField.value = nDate.getDate()+"-"+monthabbr[dPart[1]]+"-"+nDate.getFullYear();
    return true;
  }

// If failed to match, try matching input using format M/D/YY next.

    for(var i=0;i<monthno.length;i++) {
      if (dPart[0]==monthno[i] || ("0"+dPart[0])==monthno[i]) {
        dPart[0]=i;
        break;
      }
    }

    nDate = new Date(dPart[2], dPart[0], dPart[1]);
    if (isNaN(nDate) || dPart[2]!=nDate.getYear() || dPart[0]!=nDate.getMonth() || dPart[1]!=nDate.getDate()){
      return false;
    }
 
    var yyyy = (dPart[2] <= 99) ? // only two-digit year entered, default century to 2000?
    (2000 + nDate.getYear()) : nDate.getFullYear();
    theField.value = nDate.getDate()+"-"+monthabbr[dPart[0]]+"-"+yyyy;
    return true;
    
}

var dateField;
function date_validator(theField) {
  if (!dateField) dateField = theField;
  if (generic_date_validator(theField) ) {
    document.getElementById("formerror").innerHTML = "";
    dateField="";  
    return true;
  }

  document.getElementById("formerror").innerHTML = "Error: You must enter a date in the form of M/D/YY or DD-Mmm-YYYY in "+theField.name;
  setTimeout(function() {
      dateField.select();
      dateField.focus();
  },100); // focus after 10 milliseconds  return false;
  return false;
}

function validate(theForm) {
  return date_validator(theForm.f1) && date_validator(theForm.f2)
}

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37839940
Any reason for only grading a "B" ?
0
 

Author Comment

by:bluegreen288
ID: 37840634
Don't get me wrong. I appreciate the work you did very much.

I gave you full points for all the solution you offered. I graded you a B based on my personal scale of: C - not helpful; B - helpful but problem not solved, and A - problem solved.

Thanks again very much.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37841086
Then I will grade your response to my work as
"C" - asker could not be bothered letting me know the code I provided along with a demo showing it worked according to my understanding of the problem and hence not giving me a chance to improve my answer so it worked according to askers understanding of the problem...

This is not school

http://www.experts-exchange.com/help/viewHelpPage.jsp?helpPageID=26
0
 

Author Comment

by:bluegreen288
ID: 37841172
I am terribly sorry if I offended you. It was not my intent.

I've only used this forum a few times, and therefore am not familiar with the ranking system. I understood the grade to be based on the solution and NOT on the suggestions and effort you put into it.

I agree it is not school.  In fact, I tried to search Help on how to re-open my question earlier after you asked me about my grading. But I could not find anything.

If you can direct me how to re-open, I'd be more than glad to change the "grade" to an A. Given my new understanding, you deserve it.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37841240
No problem. I did not look to see how long you had been using EE or how often when I made my last comment.
And I do not like uncommented "B" grades when I have put in an effort.
An untested snippet of code where I did not follow up on questions, that would be a "B".

I would be much happier if you explained what did not work for you so I could help you fix it.
I do not need the points - I have in fact just reached 10 million points overall here. What I do like is to help people, but they have to help me help them.
So a "it did not work" does not help me fix the issue. If you managed to fix it on your own, I would like to see the solution so I can determine if I misunderstood or missed some information.
Please elaborate on the "didn't work" part.

I have unaccepted the question for you - in cases where you need moderator help, you can always click the "Request Attention"
0
 

Author Comment

by:bluegreen288
ID: 38091597
Just to let you know, I requested Attention. To be honest, I decided to postpone fixing it in favour of other more pressing development work. (It's a new application.)

Thanks again. May I approach you when I revisit?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38091628
Sure - of course!
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

If you get continual lockouts after changing your Active Directory password, there are several possible reasons.  Two of the most common are using other devices to access your email and stored passwords in the credential manager of windows.
This article discusses how to create an extensible mechanism for linked drop downs.
This video Micro Tutorial explains how to clone a hard drive using a commercial software product for Windows systems called Casper from Future Systems Solutions (FSS). Cloning makes an exact, complete copy of one hard disk drive (HDD) onto another d…
Windows 8 came with a dramatically different user interface known as Metro. Notably missing from that interface was a Start button and Start Menu. Microsoft responded to negative user feedback of the Metro interface, bringing back the Start button a…

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question