date validation

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
eppieAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

garikCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
eppieAuthor Commented:
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
eppieAuthor Commented:
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
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

garikCommented:
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
eppieAuthor Commented:
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
garikCommented:
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
eppieAuthor Commented:
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
garikCommented:
Yeap, its "validate(date.dob.value)"

0
eppieAuthor Commented:
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
eppieAuthor Commented:
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
garikCommented:
Ok, we forgot to add some action:
onClick='alert(validate(theForm.dob.value))'

0
garikCommented:
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
eppieAuthor Commented:
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
garikCommented:
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
eppieAuthor Commented:
ok, thanks. i'll play around with this some more tomorrow.

-catherine
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.