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:
Code:
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:
Code:
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...
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.
Code:
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.
This topic comes up quite often in the forum . Try using the search feature.
Code:
<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:-
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>
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.
__________________
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
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:
Code:
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
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?
__________________
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
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:
Code:
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...
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?
Code:
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:
Code:
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.
Last edited by hardhitter06; 11-05-2012 at 03:40 PM..