Solved

Problem validating values in two date fields in jsp and javascript

Posted on 2012-04-05
13
459 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
Comment Utility
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
Comment Utility
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
Comment Utility
What does partially mean. Do you have a URL?
0
 

Author Comment

by:bluegreen288
Comment Utility
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
Comment Utility
I'll take a look
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
Comment Utility
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
How does your email signature look on mobiles?

Do your employees use mobile devices to reply to emails? With mobile becoming increasingly important to the business world, it is in your best interest to make sure that your email signature looks great across all types of devices.

 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
Any reason for only grading a "B" ?
0
 

Author Comment

by:bluegreen288
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Sure - of course!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

A Bare Metal Image backup allows for the restore of an entire system to a similar or dissimilar hardware. They are highly useful for migrations and disaster recovery. Bare Metal Image backups support Full and Incremental backups. Differential backup…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

762 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now