CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   Validate Date field MM/DD/YYYY with legit date (http://www.codingforums.com/showthread.php?t=280407)

hardhitter06 11-01-2012 09:27 PM

Validate Date field MM/DD/YYYY with legit date
 
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:

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...

felgall 11-01-2012 10: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.

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.

Philip M 11-02-2012 08:57 AM

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.

hardhitter06 11-02-2012 03: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 03:34 PM

Quote:

Originally Posted by hardhitter06 (Post 1287845)
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 03: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:

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

Philip M 11-02-2012 04:58 PM

Quote:

Originally Posted by hardhitter06 (Post 1287857)
Neither are working

They work for me! :)

hardhitter06 11-02-2012 05:25 PM

haha well I must be missing something then

Philip M 11-02-2012 06: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 08:44 PM

I very well could be.

When I use your code:

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 09:12 PM

I am now trying this:

Code:

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...

felgall 11-02-2012 10:49 PM

Quote:

Originally Posted by Philip M (Post 1287797)
var nd = new Date();
nd.setFullYear(yr,mm,dd); // format YYYY,MM(0-11),DD

Surely that can be shortened to:

Code:

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

Philip M 11-03-2012 08:59 AM

Quote:

Originally Posted by felgall (Post 1288048)
Surely that can be shortened to:

Code:

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

Yes, well spotted! ;)

Philip M 11-03-2012 09:02 AM

Quote:

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 03: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?

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.


All times are GMT +1. The time now is 04:10 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.