Solved

date validation

Posted on 1997-06-02
15
525 Views
Last Modified: 2010-07-27
hi all,

i have a question about date validation.

i have a form field where the user must enter their birthdate. right now i have it checking to see that the user has entered 6 digits (or /'s) and that all they've entered is numeric:

           // validate format of birthday field MM/DD/YY
     
             var n = 0;
             var flag = new Boolean ();
             flag = true;
             for (i = test_field.value.length - 1; flag && (i >= 0); i--) {
                     ch = test_field.value.charAt(i);
                     if (ch == "0" || ch == "1" || ch == "2" || ch == "3" ||
                         ch == "4" || ch == "5" || ch == "6" || ch == "7" ||
                         ch == "8" || ch == "9") {
     
                             n++;
                             
                             }
                     else {
                             if (ch != "/") {
                                     flag = false;
                                           is_date = false;
                                }
                        }
                }
         
               if (flag && n != 6) {
                     flag = false;
                       is_date = false;
                     }      
      return is_date;
      }

however, i need to have this validate more - i need to check that the first two digits are a month (1-12), that the next two are a date (1-31) and the last two are anything. this means changing the existing validation to look for the first two digits and check them - but what if the user enters 6/28/74, for example?

has anyone done validation like this, and if so, would you mind sharing the code?

thanks,
-catherine
0
Comment
Question by:eppie
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
15 Comments
 
LVL 3

Accepted Solution

by:
garik earned 200 total points
ID: 1266122
Use a slightly different technique: instead of fixed positions go after the separators. Below is a code which uses Netscape's 3.0 split() function:

function validate(dob) {
d = dob.split("/");
return (d.length==3 && d[0]>0 && d[0]<=12 && d[1]>0 && d[1]<=31);
}

If you need help implementing split() function for older browsers, let me know.

0
 

Author Comment

by:eppie
ID: 1266123
OK, i plugged this into my existing function, like so:

      d = document.theForm.fieldname.split("/")
      if (d.length==3 && d[0]>0 && d[0]<=12 && d[1]>0 && d[1]<=31) {
            alert ("true")
      } else {
            alert("false")
      }

and when i run the function, i get the error that window.document.Form.Input.split is not a function.

any ideas?

thanks,
-catherine
0
 

Author Comment

by:eppie
ID: 1266124
wait, another comment on that.

from what i was told, i can't be assured that the user is going to enter a '/' as a separator - they may only enter the digits, or may use some other separator.

i need to check for the existance of 6 digits (0-9), and if there are 6 digits, then check the first 2 to make sure they're 01-12, and then second 2 to make sure they're 01-31.

ideas?

thanks,
-catherine


0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 3

Expert Comment

by:garik
ID: 1266125
First comment: add "value" in the following definition:
d = document.theForm.fieldname.value.split("/")
(assuming "fieldname" is the real name attribute, like <INPUT NAME=fieldname SIZE=10>)

Second comment: sometimes it's easier to guide the user instead of trying to guess which one of the numerous possibilities user might choose. In your case, I'd use more format-suggestive form of inpput for DOB, something like
<INPUT NAME=DOB_month SIZE=2> /
<INPUT NAME=DOB_day SIZE=2> /
<INPUT NAME=DOB_year SIZE=2>
<INPUT TYPE=BUTTON VALUE=Check
onClick='alert(validate(theForm.DOB_month.value,theForm.DOB_day.value,theForm.DOB_year.value));'>

and use the following function:

function validate(month, day, year) {
return (month>0 && month<=12 && day>0 && day<=31 && year>0 && year<=99);
}

This way, user avoids extra typing of separators and you avoid trouble of guessing them. In addition, setting a size of input fields you give the user an idea of how many digits is expected: f.ex., that year is only 2 digits, not 4.

0
 

Author Comment

by:eppie
ID: 1266126
i wish i could separate it into different fields for month/day/year, but the look has to match the client's spec - which has one field to enter all of the data in. it's annoying, but i have to work around it.

-catherine

0
 
LVL 3

Expert Comment

by:garik
ID: 1266127
Those clients.. :)
Ok, let's make a new array constructor which parses the string and creates an array from tokens separated by one non-digit character - we don't care which one, since most likely your client is not gonna store those separators or pay any attention to them in any other way.

function numArray(str) {
var i=0, j=0, n=0;
  for(; i<str.length; i++)
    if(isNaN(parseInt(str.charAt(i)))) {
      this[n++] = parseInt(str.substring(j,i));
      j = i+1;
    }
  this[n++] = parseInt(str.substring(j,i));
  this.length = n;
}

function validate(dob) {
  num = new numArray(dob);
  return (num.length==3 && num[0]>0 && num[0]<=12
    && num[1]>0 && num[1]<=31 && num[2]>0 && num[2]<=99);
}

0
 

Author Comment

by:eppie
ID: 1266128
OK, pardon my ability to ask lots of questions that are only slightly related, but here we go again :D

i tossed this into a mock-up form to see it it'd work right, and when i run it, i see 'str is not defined'

please tell me i'm just making a simple error somewhere ;-)

<html>
<head>
<script language="javascript">

function numArray(str) {
var i=0, j=0, n=0;
      for(; i<str.length; i++)
      if(isNaN(parseInt(str.charAt(i)))) {
      this[n++] = parseInt(str.substring(j,i));
      j = i+1;
      }
      this[n++] = parseInt(str.substring(j,i));
      this.length = n;
}

function validate(dob) {
      num = new numArray(dob);
      return (num.length==3 && num[0]>0 && num[0]<=12
      && num[1]>0 && num[1]<=31 && num[2]>0 && num[2]<=99);
}                            

</script>
</head>

<body>
<form name="date">
<input size=10 name="dob">

<p>

<input type="button" value="check date" onClick="validate(str)">
</form>

</body>
</html>
0
 
LVL 3

Expert Comment

by:garik
ID: 1266129
Yeap, its "validate(date.dob.value)"

0
 

Author Comment

by:eppie
ID: 1266130
nope, not working. grr :)
i changed the formname to 'theForm' in case 'date' is a reserved word that screws things up.

when i click the button, nothing happens:

<body>
<form name="theForm">
<input size=10 name="dob">
<p>
<input type="button" value="check date" onClick="validate(theForm.dob.value)">
</form>
</body>
0
 

Author Comment

by:eppie
ID: 1266131
OK, someone emailed me a response that i tweaked to work - this is that code. thank you so much for helping me with it this far.

<html>
<head>
<script language="javascript">

// looks for date in mm/dd/yyyy format

function checkDate(item) {
    if ( document.forms[0].item.value.length > 0 ) {
        if ( document.forms[0].item.value.length < 10 ) {
            alert(document.forms[0].item.value + ": not enough digits!");
            return false;
        } else if ( (dateArray = document.forms[0].item.value.split('/')) && (dateArray.length != 3) ) {
            alert(document.forms[0].item.value + ": must be in the format MM/DD/YYYY");
            return false;
        } else {
            if ( parseInt(dateArray[0],10) > 12 ) {
                alert(document.forms[0].item.value + ": Please make the month between 01 and 12");
                return false;
            } else if ( parseInt(dateArray[1],10) > 31 ) {
                alert(document.forms[0].item.value + ": Please make the date between 01 and 31");
                return false;
            } else {
                var date = document.forms[0].item.value.substring(0, 2) + document.forms[0].item.value.substring(3, 5) + document.forms[0].item.value.substring(6, 10);
                for (var i = 0; i < 8; i++) {
                    if ( isNaN(parseInt(date.charAt(i),10)) ) {
                        alert(document.forms[0].item.value + ": not a valid year");
                        return false;
                    }
                }
            }
        }
    }

    return true;
}      

</script>
</head>

<body>

This form will check that the user has entered a date in the
format MM/DD/YYYY.
<p>

<form name="theForm">
<input size=10 name="item">

<p>

<input type="button" value="check date" onClick="checkDate()">
</form>

</body>
</html>
0
 
LVL 3

Expert Comment

by:garik
ID: 1266132
Ok, we forgot to add some action:
onClick='alert(validate(theForm.dob.value))'

0
 
LVL 3

Expert Comment

by:garik
ID: 1266133
the problem with e-mailed solution is that it again deals only with "/" separators in a very rigid form; it won't let the client to enter 6/1/97 or 6-1-1997
0
 

Author Comment

by:eppie
ID: 1266134
but it allows me to pop up alerts telling the user exactly what format we need, rather than just the true/false.or is there a way i can do that with yours?  i prefer your solution for the brevity of it's code, but i need the flexability of warning the user exactly what their error was.

thanks,
-catherine
0
 
LVL 3

Expert Comment

by:garik
ID: 1266135
You can customize validate() any way you want:

function validate(dob) {
  num = new numArray(dob);
  if(num.length != 3) {
    alert("Please enter date as MM/DD/YY");
    return false;
  }
  if(num[0] <= 0 || num[0] > 12) {
    alert("Please enter month between 1 and 12");
    return false;
  }
  if(num[1] <= 0 || num[1] > 31) {
    alert("Please enter day between 1 and 31");
    return false;
  }
  if(num[2] < 0 || num[2] > 99) {
    alert("Please enter last two digits of the year");
    return false;
  }
  return true;
}

Although validate() is very flexible in date format, first check suggests MM/DD/YY to give a user one alternative to start with.
You can use validate() to cancel submission of the whole form:

<FORM onSubmit='return validate(this.dob.value)'>
<INPUT NAME=dob SIZE=10>
<INPUT TYPE=SUBMIT VALUE=Submit>
</FORM>

0
 

Author Comment

by:eppie
ID: 1266136
ok, thanks. i'll play around with this some more tomorrow.

-catherine
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
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…
Suggested Courses

734 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