...

View Full Version : Validate Date field MM/DD/YYYY with legit date



hardhitter06
11-01-2012, 10:27 PM
Hi All,

I've been searching all over the web and plugging in pieces of code that I have found that would accomplish a field validation maknig sure the date is in the right format and it is an actual date. Not 12/45/2012.

This is the latest piece of code I've taken from the web but this still isn't working:


function isValidDate(dateString)
{
// First check for the pattern
if(!/^\d{2}\/\d{2}\/\d{4}$/.test(dateString))
return false;

// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);

// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
return false;

var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;

// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
}


And I also have:


function validateForm( frm )
{
var oops = "";
var apptype = getRBValue( frm.elements["MoveType."] );
if ( apptype == null )
oops += "You must check Temporary or Permanent.\n";
var apptype = getRBValue( frm.elements["ResSummer."] );
if ( apptype == null )
oops += "You must check Yes or No for residential summer student.\n";
if ( trim( frm.elements["FirstName."] ).length < 2 )
oops += "You must enter your First name.\n";
if ( trim( frm.elements["LastName."] ).length < 2 )
oops += "You must enter your Last name.\n";
if ( ! emailCheck( frm.elements["Email."] ) )
oops += "That does not appear to be a valid Email Address.\n";
if (trim( frm.elements["Box."] ).length < 1 || trim( frm.elements["Box."] ).length > 4)
oops += "You must enter a Box# (Max 4 digits).\n";
if ( ! isValidDate( frm.elements["EffectiveDate."] ) )
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";
if ( trim( frm.elements["StreetAddress."] ).length < 5 )
oops += "You must enter your Street Address.\n";
if ( trim( frm.elements["City."] ).length < 4 )
oops += "You must enter your City.\n";
if ( trim( frm.elements["State."] ).length < 1 )
oops += "You must enter your State.\n";
if ( ! zipCheck( frm.elements["Zip."] ) )
oops += "You must enter a 5 digit Zip Code.\n";
// additional building and room are not validated, but they are are trimmed and upper cased
trim(frm.Apt);


var inps = frm.elements;
var chkbx = false;
for ( var i = 0; i < inps.length; ++i )
{
var inp = inps[i];
if ( inp.name.indexOf("ChkBx") > 0 && inp.value != "" && inp.checked )
{
var chkbx = true;
break;
}
}


if ( oops == "" ) return true;
alert("ERROR(S):\n" + oops);
return false;
}

Can someone show me what I'm going wrong or if there's a better piece of code out there? When I leave the field blank I get the error code but when I enter a legit date with the proper format I still get the error...

felgall
11-01-2012, 11:22 PM
The simplest way to validate a date in mm/dd/ccyy format in JavaScript is to load it into a date object and then test to make sure that the day, month and year in the date object are the same as those in the original string.


function isValidDate(dateString)
{
// First check for the pattern
if(!/^\d{2}\/\d{2}\/\d{4}$/.test(dateString))
return false;

// Parse the date parts to integers
var parts = dateString.split("/");
var day = +parts[1];
var month = +parts[0]-1;
var year = +parts[2];

if(year < 1000 || year > 3000) return false;

var dt = new Date(year, month, day);
if (dt.getDate() !== day || dt.getMonth() !== month || dt.getFullYear() !== year) return false;
return true;
}

You could shorten the code slightly more by substituting a string.match for the regexp.test and string.split so as to both validate that the code contains the three numeric values and split them into an array in a single command.

Are you sure that you are only passing the date without any leading or trailing spaces? Since you don't trim off any spaces a single space added to the date would cause it to fail validation.

Philip M
11-02-2012, 09:57 AM
This topic comes up quite often in the forum . Try using the search feature.


<script type = "text/javascript">

function checkValidDate(yr,mmx,dd) {

if (yr <1910 || yr >2012) { // you may want to change 2012 to some other year!
alert ("Year is out of range")
return false;
}

mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date();
nd.setFullYear(yr,mm,dd); // format YYYY,MM(0-11),DD

var ndmm = nd.getMonth();
if (ndmm != mm) {
alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!");
return false;
}
else {
alert (dd + "/" + mmx + "/" + yr + " is a Valid Date");
}
}

// USAGE
checkValidDate(2011,2,31) // 31st February 2011
</script>

Another way:-


<script type = "text/javascript">

String.prototype.isValidDate = function(){
var arrParts = this.split("/");
var date1 = new Date(this.toString());
dtReturn = (date1.getMonth()+1 == parseInt(arrParts[0],10) && date1.getDate() == parseInt(arrParts[1],10) && date1.getFullYear() == parseInt(arrParts[2],10) );
return dtReturn; // true or false
}

var strDate1 = "01/31/2012"; // USA date format
var strDate2 = "2/31/2012";

alert(strDate1 + ": " + strDate1.isValidDate());
alert(strDate2 + ": " + strDate2.isValidDate());

</script>

You need to make it clear to the user which format you want the date to be entered in. 3/5/2012 is 3rd May in UK and European format but is 5th March in USA format. Both are of course valid dates. You can also use a date picker or dropdowns.

Quizmaster: What relation was King Edward VIII to the Queen?
Contestant: Husband.

hardhitter06
11-02-2012, 04:14 PM
I definately need MM/DD/YYYY and I have that format written on form.

Will both of these accomplish that, I am going to give them a try in a moment. Thank you for the responses.

Philip M
11-02-2012, 04:34 PM
I definately need MM/DD/YYYY and I have that format written on form.

Will both of these accomplish that, I am going to give them a try in a moment. Thank you for the responses.

Well, try them! But you can easily alter the date format. Another way to simplify date entry is to use three separate textboxes for MM, DD and YYYY.

hardhitter06
11-02-2012, 04:51 PM
Neither are working or maybe I'm missing something with the space thing but I really don't know much.

I use forums and google searches to find code and i'm usually good enough to tweak it to what i need but I'm really struggling with this.

All I can tell you is I have an effective date field and it needs to be MM/DD/YYYY and I had this code which made sure it was in the right format:


var datechk = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/
function dateCheck( fld )
{
var effectivedate = trim( fld );
fld.value = effectivedate;
return datechk.test(effectivedate);
} (I have this commented out so it's not being used)

But nothing to make sure it was a valid date.

Should mention I tried both your pieces of code and even with a valid date I'm getting an error so again it might be a space thing...i really couldnt tell you...thanks guys

Philip M
11-02-2012, 05:58 PM
Neither are working

They work for me! :)

hardhitter06
11-02-2012, 06:25 PM
haha well I must be missing something then

Philip M
11-02-2012, 07:46 PM
Why do you say tha the scripts do not work? If you copy them into your browser and run them you will see that they do. Is the problem that you are passing the dates to the script in the wrong format?

hardhitter06
11-02-2012, 09:44 PM
I very well could be.

When I use your code:


<script type = "text/javascript">

String.prototype.isValidDate = function(){
var arrParts = this.split("/");
var date1 = new Date(this.toString());
dtReturn = (date1.getMonth()+1 == parseInt(arrParts[0],10) && date1.getDate() == parseInt(arrParts[1],10) && date1.getFullYear() == parseInt(arrParts[2],10) );
return dtReturn; // true or false
}

var strDate1 = "01/31/2012"; // USA date format
var strDate2 = "2/31/2012";

alert(strDate1 + ": " + strDate1.isValidDate());
alert(strDate2 + ": " + strDate2.isValidDate());

</script>
Read more at http://www.codingforums.com/showthread.php?p=1287633#sMCWGL9tgxfdK7AE.99

As soon as i open the form a message box opens saying those two dates you listed (01.31.12 and 2.31.12 are true.

Why is that?

BTW this is an html form...I don't know if that makes a difference.

hardhitter06
11-02-2012, 10:12 PM
I am now trying this:


function isValidDate(dateString) {
if(!/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/.test(dateString))
return false;

var parts = dateString.split("/");
var day = +parts[1];
var month = +parts[0]-1; var year = +parts[2];

if(year < 1000 || year > 3000)
return false;

var dt = new Date(year, month, day);
if (dt.getDate() !== day || dt.getMonth() !== month || dt.getFullYear() !== year) return false;
return true; }

Followed by this:


function validateForm( frm )
{
var oops = "";
var apptype = getRBValue( frm.elements["MoveType."] );
if ( apptype == null )
oops += "You must check Temporary or Permanent.\n";
var apptype = getRBValue( frm.elements["ResSummer."] );
if ( apptype == null )
oops += "You must check Yes or No for residential summer student.\n";
if ( trim( frm.elements["FirstName."] ).length < 2 )
oops += "You must enter your First name.\n";
if ( trim( frm.elements["LastName."] ).length < 2 )
oops += "You must enter your Last name.\n";
if ( ! emailCheck( frm.elements["Email."] ) )
oops += "That does not appear to be a valid Email Address.\n";
if (trim( frm.elements["Box."] ).length < 1 || trim( frm.elements["Box."] ).length > 4)
oops += "You must enter a Box# (Max 4 digits).\n";
if ( ! isValidDate( frm.elements["EffectiveDate."] ) )
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";
if ( trim( frm.elements["StreetAddress."] ).length < 5 )
oops += "You must enter your Street Address.\n";
if ( trim( frm.elements["City."] ).length < 4 )
oops += "You must enter your City.\n";
if ( trim( frm.elements["State."] ).length < 1 )
oops += "You must enter your State.\n";
if ( ! zipCheck( frm.elements["Zip."] ) )
oops += "You must enter a 5 digit Zip Code.\n";
// additional building and room are not validated, but they are are trimmed and upper cased
trim(frm.Apt);


var inps = frm.elements;
var chkbx = false;
for ( var i = 0; i < inps.length; ++i )
{
var inp = inps[i];
if ( inp.name.indexOf("ChkBx") > 0 && inp.value != "" && inp.checked )
{
var chkbx = true;
break;
}
}


if ( oops == "" ) return true;
alert("ERROR(S):\n" + oops);
return false;
}


After the rest of my functions....still doesn't work with a legit date...

felgall
11-02-2012, 11:49 PM
var nd = new Date();
nd.setFullYear(yr,mm,dd); // format YYYY,MM(0-11),DD


Surely that can be shortened to:


var nd = new Date(yr,mm,dd);

Philip M
11-03-2012, 09:59 AM
Surely that can be shortened to:


var nd = new Date(yr,mm,dd);

Yes, well spotted! ;)

Philip M
11-03-2012, 10:02 AM
As soon as i open the form a message box opens saying those two dates you listed (01.31.12 and 2.31.12) are true.

The code is

var strDate1 = "01/31/2012"; // USA date format
var strDate2 = "2/31/2012";

You must pass the date in the correct format.

hardhitter06
11-05-2012, 04:31 PM
Do I need to mention my date field (EffectiveDate) someone in this code so it knows where to pull the date from?

Aside from that question, is this code set up to validate the date in MM/DD/YYYY format?


function checkValidDate(yr,mmx,dd)
{
mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD

var ndmm = nd.getMonth();
if (ndmm != mm)
{
alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!"); return false;
}
else
{
alert (dd + "/" + mmx + "/" + yr + " is an Valid Date!"); }
}



The two lines in green are the same so how does that work?

And I have this piece of code in my function to validate the form:


if ( ! checkValidDate( frm.elements["EffectiveDate."] ) )
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";

So do I even need an alert in the function above?

Again I am a beginner with this type of stuff so I'm trying to figure it out. I appreciate your guys patience with me...I know sometimes that isn't easy.

jmrker
11-05-2012, 05:02 PM
...

function checkValidDate(yr,mmx,dd)
{
mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD

var ndmm = nd.getMonth();
if (ndmm != mm)
{
alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!"); return false;
}
else
{
alert (dd + "/" + mmx + "/" + yr + " is an Valid Date!"); }
}



...
The alert statements are NOT the same. :eek: One says Valid and the other says Invalid.
The difference in displays is the check agains the passed month value and the calculated month valued from the Date() function.

hardhitter06
11-06-2012, 03:29 PM
I appreciate the response but that doens't really help me...

Philip M
11-06-2012, 04:19 PM
function checkValidDate(yr,mmx,dd) {

The function requires the date to be passed to it in the format year,month,day, regardless of the format of the date entered by the user.

// USAGE EXAMPLE
checkValidDate(2011,2,31) // 31st February 2011


Show us your HTML for the date entry field(s).

jmrker
11-06-2012, 08:04 PM
I appreciate the response but that doens't really help me...

So what is it that you need help with? What is not working for you? What is your question?
:confused:



BTW: In your code of post #15:


if ( ! checkValidDate( frm.elements["EffectiveDate."] ) )
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";

do you really have an element named "EffectiveDate." (with the period)?
Could it perhaps be this as the problem?


if ( ! checkValidDate( frm.elements["EffectiveDate"].value ) )
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";

Show the contents of the element field. Is it formatted as MM/DD/YYYY, without any spaces?

hardhitter06
11-08-2012, 05:32 PM
I will show you all the code i have for any date related stuff in my html.

I'm using "Form to File" which submits this data to a text file. By using the "." it says what fields have been left empty if the person's web browser has javascript disabled. It's like a backup.

Here goes:



function checkValidDate(yr,mmx,dd)
{
if (yr <1910 || yr >2012)
{ // you may want to change 2012 to some other year!
alert ("Year is out of range")
return false; }
mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD
var ndmm = nd.getMonth();
if (ndmm != mm)
{ alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!");
return false;
}
else
{
alert (dd + "/" + mmx + "/" + yr + " is a Valid Date");
}
}




function validateForm( frm )
{
var oops = "";
var apptype = getRBValue( frm.elements["MoveType."] );
if ( ! checkValidDate( frm.elements["EffectiveDate"] ) )
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";

var inps = frm.elements;
var chkbx = false;
for ( var i = 0; i < inps.length; ++i )
{
var inp = inps[i];
if ( inp.name.indexOf("ChkBx") > 0 && inp.value != "" && inp.checked )
{
var chkbx = true;
break;
}
}


if ( oops == "" ) return true;
alert("ERROR(S):\n" + oops);
return false;
}

I deleted the other fields so you could just see the date one.


<td><input name="EffectiveDate." type="date" size="10">
<br>
<em>Format: MM/DD/YYYY i.e. 01/0<font face="Times New Roman, Times, serif">1</font>/2012 </em></td>
</tr>

Those are the 3 pieces...

hardhitter06
11-08-2012, 05:34 PM
I had this piece of code in earlier:


//var datechk = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/
//function dateCheck( fld )
//{
// var effectivedate = trim( fld );
// fld.value = effectivedate;
// return datechk.test(effectivedate);
//}

Which made sure the date was in the right format but didn't verify if the date was legit

jmrker
11-08-2012, 09:12 PM
I will show you all the code i have for any date related stuff in my html.

I'm using "Form to File" which submits this data to a text file. By using the "." it says what fields have been left empty if the person's web browser has javascript disabled. It's like a backup.

...

That last statement may be true for "Form to File", but I don't think it is legal JS.
Maybe some other forum members know differently (???)

Can you verify that the correct information is being sent to the validation function
by putting an alert at the start and displaying the contents passed to the function?
:confused:

hardhitter06
11-09-2012, 03:28 PM
Can you show me the alert statement i would need?

jmrker
11-09-2012, 04:06 PM
Try statements in red.


function checkValidDate(yr,mmx,dd) {
alert(yr+' '+mmx+' '+dd); // are you receiving what you expect?
if (yr <1910 || yr >2012) { // you may want to change 2012 to some other year!
alert ("Year is out of range")
return false;
}
mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD
var ndmm = nd.getMonth();
if (ndmm != mm) { alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!");
return false;
} else { alert (dd + "/" + mmx + "/" + yr + " is a Valid Date");
return true; // return results of function to if statement
}
}

Philip M
11-09-2012, 04:07 PM
Can you show me the alert statement i would need?

function checkValidDate(yr,mmx,dd) {
alert (yr + " " + mmx + " " + dd);

hardhitter06
11-26-2012, 03:37 PM
Hi guys, sorry I took so long responding but I have tried the alerts with 12/01/2012 and this is what I get when I click my Submit button:

Message from webpage: [object] undefined undefined and i click the "OK" button

Message from webpage: undefined/undefined/[object] is an Invalid Date! and i click the "OK" button

And then one last Message from webpage which is my working javascript message box letting me know all of the other fields have errors (because i only filled out the date field).

How would I fix these errors?

hardhitter06
11-26-2012, 03:44 PM
i tried both your versions of the alerts and both returned the same...

Philip M
11-26-2012, 05:10 PM
You are passing the date to the script as a single string, but it expects three separate values for year, month and day.

Try this:-


<script type = "text/javascript">

function checkValidDate(which) {
var s = which.replace(/[\-\s]/gi,"/"); // change hyphens or spaces to /
var sp = s.split("/");
var yr = sp[2];
var mmx = sp[0];
var dd = sp[1];

alert(yr+' '+mmx+' '+dd); // are you receiving what you expect?
if (yr <1910 || yr >2012) { // you may want to change 2012 to some other year!
alert ("Year is out of range");
return false;
}

mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD
var ndmm = nd.getMonth();
if (ndmm != mm) {
alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!");
return false
}
else {
alert (dd + "/" + mmx + "/" + yr + " is a Valid Date");
return true; // return results of function to if statement
}
}

</script>

ENTER DATE AS MM/DD/YYYY <input name="EffectiveDate." type="text" size="10" onblur = "checkValidDate(this.value)">

Note that your input field is "text", not "date".

hardhitter06
11-26-2012, 05:23 PM
Ive made the respective changes to both but i think there is a syntax error in the new code because the submit button is bypassing my javascript validations.

in other words, the error message is not popping up now for any of the fields now

Philip M
11-26-2012, 05:33 PM
There is no syntax error in the code I gave you.

Have you tried using your error console?

hardhitter06
11-26-2012, 05:39 PM
Philip,

I've been trying to figure this out for a long *** time and you and jmrker have been great trying to walk me through this.

Is there any way i could email you my file and you could take a look at it that way to prevent wasting more of your time?

Philip M
11-26-2012, 05:50 PM
Philip,

I've been trying to figure this out for a long *** time and you and jmrker have been great trying to walk me through this.

Is there any way i could email you my file and you could take a look at it that way to prevent wasting more of your time?

Speaking for myself, I am sorry but I do not offer a free private coding service. I am happy to answer questions in the forum, but the real problem is that you do not have enough knowledge/experience to apply the information you have been given.

One more time - have you tried using your error console?

Have you tried placing alerts at strategic locations in the code to inspect the values or see whether a function is being executed?

hardhitter06
11-26-2012, 06:44 PM
I have this:

function checkValidDate(which) {
var s = which.replace(/[\-\s]/gi,"/"); // change hyphens or spaces to /
var sp = s.split("/");
var yr = sp[2];
var mmx = sp[0];
var dd = sp[1];

alert(yr+' '+mmx+' '+dd); // are you receiving what you expect?
if (yr <1910 || yr >2012) { // you may want to change 2012 to some other year!
alert ("Year is out of range");
return false;
}

mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD
var ndmm = nd.getMonth();
if (ndmm != mm) {
alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!");
return false
}
else {
alert (dd + "/" + mmx + "/" + yr + " is a Valid Date");
return true; // return results of function to if statement
}
}

My javascript isnt being triggered with the extra code now...I've been looking through it and can't figure out why. Error console gives me no indication why.

Philip M
11-26-2012, 06:56 PM
I have this:

function checkValidDate(which) {
var s = which.replace(/[\-\s]/gi,"/"); // change hyphens or spaces to /
var sp = s.split("/");
var yr = sp[2];
var mmx = sp[0];
var dd = sp[1];

alert(yr+' '+mmx+' '+dd); // are you receiving what you expect?
if (yr <1910 || yr >2012) { // you may want to change 2012 to some other year!
alert ("Year is out of range");
return false;
}

mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD
var ndmm = nd.getMonth();
if (ndmm != mm) {
alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!");
return false
}
else {
alert (dd + "/" + mmx + "/" + yr + " is a Valid Date");
return true; // return results of function to if statement
}
}

My javascript isnt being triggered with the extra code now...I've been looking through it and can't figure out why. Error console gives me no indication why.



What happened to

ENTER DATE AS MM/DD/YYYY <input name="EffectiveDate." type="text" size="10" onblur = "checkValidDate(this.value)">

The code I gave you works for me. :)

In future you should show your (relevant) HTMLas well as your (relevant) Javascript.

hardhitter06
11-26-2012, 07:08 PM
function validateForm( frm )
{
var oops = "";
var apptype = getRBValue( frm.elements["MoveType."] );
if ( apptype == null )
oops += "You must check Temporary or Permanent.\n";
var apptype = getRBValue( frm.elements["ResSummer."] );
if ( apptype == null )
oops += "You must check Yes or No for residential summer student.\n";
if ( trim( frm.elements["FirstName."] ).length < 2 )
oops += "You must enter your First name.\n";
if ( trim( frm.elements["LastName."] ).length < 2 )
oops += "You must enter your Last name.\n";
if ( ! emailCheck( frm.elements["Email."] ) )
oops += "That does not appear to be a valid Email Address.\n";
if (trim( frm.elements["Box."] ).length < 1 || trim( frm.elements["Box."] ).length > 4)
oops += "You must enter a Box# (Max 4 digits).\n";
if ( ! checkValidDate( frm.elements["EffectiveDate."] ) )
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n"; if ( trim( frm.elements["StreetAddress."] ).length < 5 )
oops += "You must enter your Street Address.\n";
if ( trim( frm.elements["City."] ).length < 4 )
oops += "You must enter your City.\n";
if ( trim( frm.elements["State."] ).length < 1 )
oops += "You must enter your State.\n";
if ( ! zipCheck( frm.elements["Zip."] ) )
oops += "You must enter a 5 digit Zip Code.\n";
// additional building and room are not validated, but they are are trimmed and upper cased
trim(frm.Apt);


var inps = frm.elements;
var chkbx = false;
for ( var i = 0; i < inps.length; ++i )
{
var inp = inps[i];
if ( inp.name.indexOf("ChkBx") > 0 && inp.value != "" && inp.checked )
{
var chkbx = true;
break;
}
}


if ( oops == "" ) return true;
alert("ERROR(S):\n" + oops);
return false;
}}


<td><input name="EffectiveDate." type="text" size="10" onblur = "checkValidDate(this.value)">
<br>
<em>Format: MM/DD/YYYY i.e. 01/0<font face="Times New Roman, Times, serif">1</font>/2012 </em></td>

Haha I believe you Philip. This code is weird though - sometimes when I add new stuff even if there are no errors in it, it breaks my javascript validation.

I've tried copying it all and putting the code in a fresh file but that isn't working either.

jmrker
11-27-2012, 04:15 PM
In EVERY ONE of your 'if...' statements, put in the associated braces {} to complete the logic.

For example:


if ( ! checkValidDate( frm.elements["EffectiveDate."] ) )
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n"; if ( trim( frm.elements["StreetAddress."] ).length < 5 )
oops += "You must enter your Street Address.\n";

should be:


if ( ! checkValidDate( frm.elements["EffectiveDate."] ) ) {
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n"; }
if ( trim( frm.elements["StreetAddress."] ).length < 5 ) {
oops += "You must enter your Street Address.\n"; }


This may not solve the problem, but it would make it infinitely easier to read and decide upon the status of each condition.

Another thought:
You should remove or rename each element with a '.' character from your element names and assignments.
AFAIK, I don't think it is a valid character as there should be alpha-numeric and '_' characters only in the names.

hardhitter06
11-27-2012, 05:04 PM
Ok I put the {} around each "if" but my validation is still not triggering.

There is something in the function checkValidDate that is screwing with my code. I'm sure Philip has the right code but for some reason it isn't meshing with my code properly. I can't even check if the date validation is working properly because the javascript as a whole isn't working.

Regarding the "." in the field names, they are used with this "Form to File" set up for this HTML form so that if someone has javascript disabled on their web browser it will still trigger the fields that haven't been filled in.

I removed the "." for effective date to eliminate that from being a possible issue.

hardhitter06
11-27-2012, 05:07 PM
i got excited and noticed one of the "return false" didnt have a following ";" but that didn't correct the problem.

Also, I know we were using a couple of the alerts to check the code but I don't think any are needed in the function since my final function of validating the form alerts the users if a field hasn't been filled out properly. So Philips function purely needs to run the date through to check and see if it's an actual date. Then the final function will alert them in the returned date is incorrect...

I may have worded that funny but I have the same type of set up for email check (which basically makes sure there is an @ in the email).

Textbox for email:
<input name="Email." type="text" size="30">

Function for email:

var echk = /^([a-z][\w\-\'\.]*)+\@([a-z][\w\-\'\.]+\.)+[a-z]{2,6}$/i
function emailCheck( fld )
{
var email = trim( fld );
fld.value = email;
return echk.test(email);
}


Function ValidateForm that shows errors to end user:



function validateForm( frm )
{
var oops = "";
if ( ! emailCheck( frm.elements["Email."] ) ) {
oops += "That does not appear to be a valid Email Address.\n"; }

if ( oops == "" ) return true;
alert("ERROR(S):\n" + oops);
return false;
}


[Just cut out the email field]

So I need the EffectiveDate to follow the same process..I don't know if thats how Philip's code is currently set up to do that.

Philip M
11-27-2012, 06:01 PM
I have to say that this is getting a little tedious.

It seems likely (certain in fact if none of your Javascript works) that your code contains syntax errors which prevent the script from working. jmrker has pointed out . (periods) in names which are invalid. You must not use any punctuation marks of any kind in a JavaScript variable name, other than the underscore.

You seem to be trying to doctor a validation script you have copied from somewhere without understanding any limitations which may apply.

Show your (relevant) stripped down code relating to the date entry (only) - not other fields. Both HTML and Javascript. Don't confuse the issue with code for validating something else..

It is far better IMO to alert the user to input errors as they arise rather than storing them up until the final validation.

To check for a blank field (my script checks that the date entered is valid)


if (frm.elements["EffectiveDate."].value == "" ) {
oops += "You must enter your Effective Date of Move";
}

hardhitter06
11-27-2012, 06:17 PM
Well the problem is my Javascript worked until I put your code in. You can say all you want about me not understanding this which is partially true but the fact of the matter is it worked until I added your DateValidate function. And I thought forums were intended to help people that don't have all of the knowledge. I made you aware in the early goings that I lack experience but I've been working hard to learn this stuff through the process of this thread so give me some credit .

I previously had a Date validation that at least made sure it was in the right format (didn't check to make sure it was an actual date) and my javascript triggered sooooo not trying to be offensive but there is something in your code that is breaking the link to my ValidateForm function.

Please ignore the periods in the names...they worked with them before and with this "Form to File" i need to have them. They are not the issue.

I showed you the email check only to show you the process of how my functions are set up. Again, I don't need to alert the user if they filled out the wrong date when they are at the field, odds are this will be a rare error so showing them all of the errors when they click the submit button is fine.

Here are the 3 pieces of code [Input field, your function, my function]


<input name="EffectiveDate" type="text" size="10" onblur="checkValidDate(this.value)">


function checkValidDate(which) {
var s = which.replace(/[\-\s]/gi,"/"); // change hyphens or spaces to /
var sp = s.split("/");
var yr = sp[2];
var mmx = sp[0];
var dd = sp[1];

if (yr <1910 || yr >2012) { // you may want to change 2012 to some other year!
return false;
}

mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD
var ndmm = nd.getMonth();
if (ndmm != mm)
{
alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!");
return false;
}
else {
alert (dd + "/" + mmx + "/" + yr + " is a Valid Date");
return true; // return results of function to if statement
}
}


function validateForm( frm )
{
var oops = "";
if ( ! checkValidDate( frm.elements["EffectiveDate"] ) ) {
oops += "You must enter your Effective Date of Move in the proper format (MM/DD/YYYY).\n";}

if ( oops == "" ) return true;
alert("ERROR(S):\n" + oops);
return false;
}


Full source code can be see here: http://www.albany.edu/~StuAddCh/index.html

Philip M
11-27-2012, 06:26 PM
The code I gave you (repeated here) works just fine for me. So the fault, dear Brutus, lies not in the stars ......


ENTER DATE IN MM/DD/YYYY FORMAT <input name="EffectiveDate" type="text" size="10" onblur="checkValidDate(this.value)">

<script type = "text/javascript">

function checkValidDate(which) {
var s = which.replace(/[\-\s]/gi,"/"); // change hyphens or spaces to /
var sp = s.split("/");
var yr = sp[2];
var mmx = sp[0];
var dd = sp[1];

if (yr <1910 || yr >2012) { // you may want to change 2012 to some other year!
return false;
}

mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD
var ndmm = nd.getMonth();
if (ndmm != mm)
{
alert (dd + "/" + mmx + "/" + yr + " is an Invalid Date!");
return false;
}
else {
alert (dd + "/" + mmx + "/" + yr + " is a Valid Date");
return true; // return results of function to if statement
}
}
</script>

Your final validation only needs to check that a date entry (which if made must be a valid date) has been made. If not, (field is blank) trigger the message.


if (frm.elements["EffectiveDate."].value == "" ) {
oops += "You must enter your Effective Date of Move";
}

The checkValidDate() function requires the value of the input field to be passed to it. Try:-

if ( ! checkValidDate(frm.elements["EffectiveDate."].value ) ) {

007julien
11-27-2012, 06:59 PM
Why impose both separators and leading zeros?

The leading zeros are made to remove the separator? Are they not ?

You must allow dates as MMDDYYYY !

Separators may allow the user to see clearly? So they must be left to his choice. Under these conditions, It should be possible to authorize the use of separators with or without leading zeros.

Then a script could he not take this form?


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
<style type="text/css">
#pge {width:200px;}
p{margin:3px auto;}
input{display:block;margin:0 auto;text-align:center}
</style>
</head>
<body>
<div id="pge"><fieldset><legend>Enter a date</legend>
<p><input id="dte" type="txt" onchange="tst()"></p>
<p id="rsp">&nbsp;</p>
</<fieldset></div>
<script type="text/javascript">
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,'')}

function tst(){
var str=document.getElementById('dte').value, month, date, year;
var rgx=/0?([1-9]{1,2})[\D]*0?([1-9]{1,2})[\D]*([1-9]{4})/;
// A replace method with an anonymous function to define month, date and year
str.trim().replace(rgx,
function(all,b1,b2,b3){month=+b1;date=+b2;year=+b3;});
if (isNaN(month)||isNaN(date)||isNaN(year)) {document.getElementById('rsp').innerHTML='Please, enter a valid date with digits, separators or leading zeros (M/D/YYYY or MM/DD/YYYY)';return}
var dat=new Date(year, month-1, date);
if (dat.getMonth()!=month-1) {document.getElementById('rsp').innerHTML='Sorry, this date seems not valid !';return}
// If you insist absolutely on this redundant form. You write It !
else document.getElementById('dte').value=(month<10?'0':'')+month+'/'+(date<10?'0':'')+date+'/'+year;
}
</script>
</body>
</html>This function works with any separators, residual spaces or leading zeros !

hardhitter06
11-27-2012, 07:30 PM
Philip/JMrker,

This is weird but it finally worked!!!

Philip, I made the change to the validate form piece of code and tested - javascript still didnt trigger. I then commented out everything that had to do with effectivedate and my validation triggered. I then only commented out Philips function and activated the piece in the validate form but still no javascript trigger. I then swapped that and allowed Philips function and commented out the piece in the validate form and the validation triggered. I then activated all of the code again and the freaking thing worked lol...go figure...

Anyways I will provide the three pieces of code for anyone else who may find use with this. I want to thank you both a million times for the patience you had with me through this tedious mess lol...soo thanks!! have a great day guys.

[Field code, Phillips DateValidate function, my ValidateForm function]


<input name="EffectiveDate" type="text" size="10" onBlur="checkValidDate(this.value)">



function checkValidDate(which) {
var s = which.replace(/[\-\s]/gi,"/"); // change hyphens or spaces to /
var sp = s.split("/");
var yr = sp[2];
var mmx = sp[0];
var dd = sp[1];

if (yr < 2012) { // you may want to change 2012 to some other year!
return false;
}

mm = mmx-1; // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd); // format YYYY,MM(0-11),DD
var ndmm = nd.getMonth();
if (ndmm != mm)
{
//alert (mmx+ "/" + dd + "/" + yr + " is an Invalid Date!");
return false;
}
else {
//alert (mmx + "/" + dd + "/" + yr + " is a Valid Date");
return true; // return results of function to if statement
}
}



function validateForm( frm )
{
var oops = "";
if ( ! checkValidDate(frm.elements["EffectiveDate"].value ) ) {
oops += "You must enter your Effective Date of Move. \n" ; }
if ( oops == "" ) return true;
alert("ERROR(S):\n" + oops);
return false;
}

Philip M
11-27-2012, 08:02 PM
Glad to hear that you have got it working! :) I think that at some stage you introduced a syntax error when you commented out part of the code.

007julien
11-28-2012, 07:36 PM
Sorry, I make a mistake with the regular expression. The right regular expression is to find ...

EDIT : Perhaps this one which allow one digit followed by a separator or two digits for month and date

var rgx=/(\d(?=\D)|\d\d)[\D]*(\d(?=\D)|\d\d)[\D]*([0-9]{4})/;



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum