How can you validate a date string in a form text field?

Jorge Jordão

  • There's no built-in function for validating a date string in JavaScript (like VBScript's isDate).
  • You can find a nice form validating library at Netscape's developer site, including an isDate(year,month,day) function.
  • Usually, the easiest way to do it is split the date elements in separate form elements, so you won't have to worry about the date format used.
    <HTML>
      <HEAD>
        <SCRIPT LANGUAGE="JavaScript" SRC="FormChek.js"></SCRIPT>
        <SCRIPT LANGUAGE="JavaScript">   
          function onSubmit(form) {
            with (form) {
              var yearValue = year.value;
              var monthValue = month.options[month.selectedIndex].value;
              var dayValue = day.value;
              if (!isDate(yearValue,monthValue,dayValue)) {
                alert("Invalid date!");
                return false;
              }
            }
            return true;
          }
        </SCRIPT>        
      </HEAD>
      <BODY>
        <FORM ONSUBMIT="return onSubmit(this)">
          <INPUT TYPE="text" NAME="year" SIZE="4" MAXLENGTH="4">
          <SELECT NAME="month">
            <OPTION VALUE="1">January
            <!-- put other months here -->
          </SELECT>
          <INPUT TYPE="text" NAME="day" SIZE="2" MAXLENGTH="2">
          <INPUT TYPE="submit" VALUE="Validate">           
        </FORM>
      </BODY>
    </HTML>
    
  • If however you want to keep the date as a single text field, then you must split the individual elements (using the split(separator) String function) before validating them. In that case, you must assume one (or a group of) possible date formats (e.g. yyyy-mm-dd).
    <HTML>
      <HEAD>
        <SCRIPT LANGUAGE="JavaScript" SRC="FormChek.js"></SCRIPT>
        <SCRIPT LANGUAGE="JavaScript">   
          function onSubmit(form) {
            with (form) {
              // assuming yyyy-mm-dd format
              var dateArray = date.value.split('-');
              if (dateArray.length!=3) {
                alert("Invalid date!");
                return false;                    
              }
              var yearValue = dateArray[0];
              var monthValue = dateArray[1];
              var dayValue = dateArray[2];
              if (!isDate(yearValue,monthValue,dayValue)) {
                alert("Invalid date!");
                return false;
              }
            }
            return true;
          }
        </SCRIPT>        
      </HEAD>
      <BODY>
        <FORM ONSUBMIT="return onSubmit(this)">
          <INPUT TYPE="text" NAME="date" SIZE="10" MAXLENGTH="10">
          <INPUT TYPE="submit" VALUE="Validate">           
        </FORM>
      </BODY>
    </HTML>
    
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact