Solved

Problem validating values in two date fields in jsp and javascript

Posted on 2012-04-05
13
462 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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

When you start your Windows 10 PC and got an "Operating system not found" error or just saw  "Auto repair for startup" or a blinking cursor with black screen. A loop for Auto repair will start but fix nothing.  You will be panic as there are no back…
Possible fixes for Windows 7 and Windows Server 2008 updating problem. Solutions mentioned are from Microsoft themselves. I started a case with them from our Microsoft Silver Partner option to open a case and get direct support from Microsoft. If s…
The viewer will learn how to successfully create a multiboot device using the SARDU utility on Windows 7. Start the SARDU utility: Change the image directory to wherever you store your ISOs, this will prevent you from having 2 copies of an ISO wit…
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…

786 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