Solved

Javascript Date Validation Problem

Posted on 2007-11-29
10
3,108 Views
Last Modified: 2010-04-21
I have a code that validates the date input in the text field DD/MM/YYYY. The date validation code works fine "alone". When I integrate the code with the other form validation scripts, it keeps saying the date field is in the wrong format! I hv tried writing n copying lots of date validation code that works fine but when I integrate it, it fails.

I marked the part where I'm hving problem with the code. The attached code is very long as it has many show hide layer functions. If you think this is too messy to read, can you suggest or even help me build the date validation script that can integrate seamlessly? Many thanks.
//Show/Hide Layers

<!-- 

function showhide(layer_ref, thestate) { 

var state = thestate;

if (document.all) { //IS IE 4 or 5 (or 6 beta) 

eval( "document.all." + layer_ref + ".style.display = state"); 

} 

if (document.layers) { //IS NETSCAPE 4 or below 

document.layers[layer_ref].display = state; 

} 

if (document.getElementById &&!document.all) { 

hza = document.getElementById(layer_ref); 

hza.style.display = state; 

} 

} 

//-->

function gup(name){  

name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  

var regexS = "[\\?&]"+name+"=([^&#]*)";  

var regex = new RegExp( regexS );  

var results = regex.exec( window.location.href );  

if( results == null ){   

return "";  

}

else{    

return results[1];

}

}

function IsNumeric(sText)

{

   var ValidChars = "0123456789";

   var IsNumber=true;

   var Char;
 

 

   for (i = 0; i < sText.length && IsNumber == true; i++) 

      { 

      Char = sText.charAt(i); 

      if (ValidChars.indexOf(Char) == -1) 

         {

         IsNumber = false;

         }

      }

   return IsNumber;

   

  }
 

function validate(theForm)

{

	

	if (theForm.GPN.value == ""){

		alert("Please enter a GPN value.");

		theForm.GPN.focus();

		return(false);

	}

	if (theForm.GPN.value.length < 8){

		alert("Please enter a valid 8 digit GPN number.");

		theForm.GPN.focus();

		return(false);

	}

	if (IsNumeric(theForm.GPN.value) == false){

		alert("Please enter a valid GPN numerical value.");

		theForm.GPN.focus();

		return(false);

	}

	if (theForm.name.value == ""){

		alert("Please enter your Name.");

		theForm.name.focus();

		return(false);

	}

	if (theForm.location.value == "select"){

		alert("Please select a Location value.");

		theForm.location.focus();

		return(false);

	}

	if (theForm.location.value == "Hong Kong"){

		

		if (theForm.requesttype_hongkong.value == "select"){

			alert("Please select a Request Type value.");

			theForm.requesttype_hongkong.focus();

			return(false);

		}

	

		if (theForm.requesttype_hongkong.value == "Visa Letter"){

			if (theForm.country_of_visit.value == ""){

				alert("Please enter a Country of Visit value.");

				theForm.country_of_visit.focus();

				return(false);

			}

			

		var tripstartdate = theForm.start_date_of_trip.value;

		var tripenddate = theForm.end_date_of_trip.value;

		dt1=getDateObject(tripstartdate,"/");

		dt2=getDateObject(tripenddate,"/");

			if(dt1>dt2) {

				alert("Please enter in an End Date of Trip that is on or after Start Date of Trip.");			

				theForm.end_date_of_trip.focus();

				return(false);

			}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		var sdt=theForm.start_date_of_trip.value;

			if (!isDate(sdt,0))

				{alert("Input the date in the correct format(DD/MM/YYYY)!");

				theForm.start_date_of_trip.focus();

				return(false);}
 

		var edt=theForm.end_date_of_trip.value;

			if (!isDate(edt,0))

				{alert("Input the date in the correct format (DD/MM/YYYY)!");

				theForm.start_date_of_trip.focus();

				return(false);}				

		}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		if (theForm.requesttype_hongkong.value == "Employment Reference Letter (with Salary Only)"){

			if (theForm.show_salary.value == "select"){

				alert("Please a Salary Details option.");

				theForm.show_salary.focus();

				return(false);

			}

		}

		if (theForm.requesttype_hongkong.value == "Physical Check-up Letter"){

			if (theForm.checkupdate.value == ""){

				alert("Please enter a check up date.");

				theForm.checkupdate.focus();

				return(false);

			}

			if (theForm.checkup_clinic.value == "select"){

				alert("Please select a clinic.");

				theForm.checkup_clinic.focus();

				return(false);

			}

		}

	}

	

	}

			

	

	var curDateTime = new Date();

    theForm.timestamp.value = curDateTime;

	return(true);

}
 

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 

function isDigit(theDigit)

{

var digitArray = new Array('0','1','2','3','4','5','6','7','8','9'),j;
 

for (j = 0; j < digitArray.length; j++)

{if (theDigit == digitArray[j])

return true

}

return false
 

}
 

function isPositiveInteger(theString)

{

var theData = new String(theString)
 

if (!isDigit(theData.charAt(0)))

if (!(theData.charAt(0)== '+'))

return false
 

for (var i = 1; i < theData.length; i++)

if (!isDigit(theData.charAt(i)))

return false

return true

}
 

function isDate(s,f)

{var a1=s.split("/");

var a2=s.split("-");

var e=true;

if ((a1.length!=3) && (a2.length!=3))

{

e=false;

}

else

{if (a1.length==3)

var na=a1;

if (a2.length==3)

var na=a2;

if (isPositiveInteger(na[0]) && isPositiveInteger(na[1]) && isPositiveInteger(na[2]))

{ if (f==1)

{var d=na[1],m=na[0];

}

else

{var d=na[0],m=na[1];

}

var y=na[2];

if (((e) && (y<1000)||y.length>4))

e=false

if (e)

{

v=new Date(m+"/"+d+"/"+y);

if (v.getMonth()!=m-1)

e=false;

}

}

else

{

e=false;

}

}

return e

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function getDateObject(dateString,dateSeperator)

{

	//This function return a date object after accepting 

	//a date string ans dateseparator as arguments

	var curValue=dateString;

	var sepChar=dateSeperator;

	var curPos=0;

	var cDate,cMonth,cYear;
 

	//extract day portion

	curPos=dateString.indexOf(sepChar);

	cDate=dateString.substring(0,curPos);

	

	//extract month portion				

	endPos=dateString.indexOf(sepChar,curPos+1);			

	cMonth=dateString.substring(curPos+1,endPos);
 

	//extract year portion				

	curPos=endPos;

	endPos=curPos+5;			

	cYear=curValue.substring(curPos+1,endPos);

	

	//Create Date Object

	dtObject=new Date(cYear,cMonth,cDate);	

	return dtObject;

}

Open in new window

0
Comment
Question by:jannhan
  • 5
  • 4
10 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
This is wrong - the return is outside the function

      } <<<<<<< too many??
                  
      
      var curDateTime = new Date();
    theForm.timestamp.value = curDateTime;
      return(true);
}


Can you show the page with the form too?
0
 
LVL 7

Expert Comment

by:Maverick_Cool
Comment Utility
Just do alert of vlue of the text field before validating, u will have answere in fornt of eye. Alert javascript primitive debugging technique.
0
 

Author Comment

by:jannhan
Comment Utility
} <----- i dont think is this problem. When I take out the date validation functions n the alert, it works fine. This is the form field, when user click on the input field, a calendar will pop out. If the user close the calendar, they will be able to enter free text. I want a date validation here. But I'm baffled as to why a perfect date validation script works but when I integrate it with other form validation scripts it fails. Do you have a more simple way of validating date?

 <TD class=formfield colSpan=3><INPUT  id=start_date_of_trip   onclick="cal.select(document.forms['theForm'].start_date_of_trip,'start_date_of_trip','dd/MM/yyyy'); return false;" name=start_date_of_trip> <A id=anchor1 onclick="cal.select(document.forms['theForm'].start_date_of_trip,'anchor1','dd/MM/yyyy'); return false;" href="# name=anchor1><IMG height=16 src="HR Global - APAC - Online Request Form_files/calendar_aktiv.gif"                      width=16></A> *</TD></TR>
                    <TR>
0
 

Author Comment

by:jannhan
Comment Utility
sorry guys...let me rephrase my question. In the code I have validate date format and compare the dates so end date is always later than start date. However when I combine this two validation scripts together, only the validate date format works n compare date cannot work. It keeps saying date format is wrong.

When I remove either one of it, the validation works. Pls advice.

function validateDate(theForm){
 

//validate date in dd/mm/yyyy format

var d1 = (theForm.start_date_of_trip.value).split("/");

var d2 = new Date(d1[2], d1[1]-1, d1[0]);

var d3 = (theForm.end_date_of_trip.value).split("/");
 

if((d1[2]!=d2.getFullYear() || d1[1]!=d2.getMonth()+1 || d1[0]!=d2.getDate())){

 alert("Invalid date, Please enter the date in dd/mm/yyyy format");

 theForm.start_date_of_trip.focus();

return false;

}
 

if((d3[2]!=d2.getFullYear() || d3[1]!=d2.getMonth()+1 || d3[0]!=d2.getDate())){

 alert("Invalid date, Please enter the date in dd/mm/yyyy format");

 theForm.end_date_of_trip.focus();

return false;

}
 

//validate end date is later than start date

dt1=getDateObject(tripstartdate,"/");

dt2=getDateObject(tripenddate,"/");

if(dt1>dt2) {

alert("Please enter in an End Date of Trip that is on or after Start Date of Trip.");theForm.end_date_of_trip.focus();

return(false);}

}
 

function getDateObject(dateString,dateSeperator)

{

	//This function return a date object after accepting 

	//a date string ans dateseparator as arguments

	var curValue=dateString;

	var sepChar=dateSeperator;

	var curPos=0;

	var cDate,cMonth,cYear;
 

	//extract day portion

	curPos=dateString.indexOf(sepChar);

	cDate=dateString.substring(0,curPos);

	

	//extract month portion				

	endPos=dateString.indexOf(sepChar,curPos+1);			

	cMonth=dateString.substring(curPos+1,endPos);
 

	//extract year portion				

	curPos=endPos;

	endPos=curPos+5;			

	cYear=curValue.substring(curPos+1,endPos);

	

	//Create Date Object

	dtObject=new Date(cYear,cMonth,cDate);	

	return dtObject;

}

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
Please post the script and the html so we can test it without having to write our own test cases
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:jannhan
Comment Utility
Pls have a look at the second scripts I posted. I hv identified that the problems lie in there. Ignore the original scripts pls.  
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
Comment Utility
Be consistent:
<script>

function validateDate(theForm){

  var tripstartdate = theForm.start_date_of_trip.value;

  var tripenddate = theForm.end_date_of_trip.value;

  var dt1=getDateObject(tripstartdate,"/");

  var dt2=getDateObject(tripenddate,"/");

 

  //validate date in dd/mm/yyyy format

  var d1 = (tripstartdate).split("/");

  var d2 = (tripenddate).split("/");

 

  if((d1[2]!=dt1.getFullYear() || d1[1]!=dt1.getMonth()+1 || d1[0]!=dt1.getDate())){

    alert("Invalid date, Please enter the date in dd/mm/yyyy format");

    theForm.start_date_of_trip.focus();

    return false;

  }

 

  if((d2[2]!=dt2.getFullYear() || d2[1]!=dt2.getMonth()+1 || d2[0]!=dt2.getDate())){

    alert("Invalid date, Please enter the date in dd/mm/yyyy format");

    theForm.end_date_of_trip.focus();

    return false;

  }

  //validate end date is later than start date

  if(dt1>dt2) {

    alert("Please enter in an End Date of Trip that is on or after Start Date of Trip.");

    theForm.end_date_of_trip.focus();

    return false;

  }

  return true; // allow submission

}

 

function getDateObject(dateString,dateSeparator) {

  var parts = (dateString).split(dateSeparator);

  return new Date(parts[2],parts[1]-1,parts[0],0,0,0);	

}

</script>

Open in new window

0
 

Author Closing Comment

by:jannhan
Comment Utility
can i know where i did wrong?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
In the first script you surely had a paste problem

In the last posted script you forgot the

var tripstartdate = theForm.start_date_of_trip.value;
var tripenddate = theForm.end_date_of_trip.value;

I just rewrote the whole thing to use the getDateObject and then rewrote that too since it was overly complex for your use....
0
 

Author Comment

by:jannhan
Comment Utility
thanks :-)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
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)
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

771 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