Solved

date validation

Posted on 1997-06-02
15
510 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
  • 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
 
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
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

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
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…

747 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

15 Experts available now in Live!

Get 1:1 Help Now