How to Validate a Date Using JavaScript

104 24
    • 1). Create a new HTML file in an editor or in the Notepad. Add a form to the document with a date input and name the date input so it can be referenced through JavaScript. Create a submit button and set the value to a JavaScript function to validate the date. For example, type:

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <html xmlns="http://www.w3.org/1999/xhtml">

      <head>

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

      <title>Validate Date</title>

      </head>

      <body>

      <form name="frm">Enter a date in the form mm/dd/yyyy: <input type="text" name="dt" /><br/>

      <input type="submit" name="submit" value="Submit" onclick="validateDate()" /></form>

      </body>

      </html>

    • 2). Create a JavaScript function and place it between the <head> tags. Access the user-input date value using its name on the form. Test the value against a regular expression to validate the format. Use the same regular expression to separate the month, day and year elements into an array, and pass the array to a function that will validate the logic of the inputs. For example, type:

      <script type="text/javascript">

      function validateDate() {

      var format = /^($0?\d)\/(0?\d)\/(\d(4))$/;

      var dt = document.frm.dt;

      if (!format.test(dt) || !checkDate(format.exec(document.frm.dt)))

      alert("Please enter a date in the format mm/dd/yyyy");

      }

    • 3). Create the JavaScript function to validate the logic of the elements of the date value. Access the month, day and year from the array passed to the function. For example, type:

      function checkDate(values) {

      var month = paraseInt(values[1]);

      var day = parseInt(values[2]);

      var year = parseInt(values[3]);

    • 4). Check that the month is between one and 12 and that the day is either 30 or 31. For example, type:

      if (month<1 || month>12 || (day<30 || day>31)) return false;

    • 5). Check that the number of days is 30 for April, June, September and November, or 31 for all other months. For example, type:

      switch (month) {

      case 4: case 6: case 9: case 11:

      if (day != 30) return false;

      break;

      default:

      if (day != 31) return false;

      break;

      }

    • 6). Check that the year is between 1 and 32767. For example, type:

      if (year<1 || year>32767) return false;

    • 7). Return true if the date string passed all validation tests. For example, type:

      return true;

      }

      </script>

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.