title: JavaScript Detecting Valid Dates
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript">Detecting an &ldquo;invalid date&rdquo; Date instance in JavaScript</a>  </p>
  </blockquote>
  
  
  
  <p>I was using the following to detect a valid date:</p>
  
  <pre><code>var text = $('#Date').val();
  var date = Date.parse(text);
  
  if (isNaN(date)) {
        // Invalid date
  }
  </code></pre>
  
  <p>But found that Date.parse thinks the following are valid dates (mm/dd/yyyy)</p>
  
  <ul>
  <li>2/30/2011 </li>
  <li>11/31/2011</li>
  </ul>
  
  <p>Any other way to detect invalid dates when the number of days surpasses the total number of 
  days in the month?</p>
  
  <p>UPDATE: An even larger problem is that the jQuery validation plugin doesn't detect this as an invalid date either!</p>
  
  <p>SOLUTION:</p>
  
  <p>Based on @Guffa's comments I have created the following function to validate dates:</p>
  
  <pre><code>function validDate(text) {
  
      var date = Date.parse(text);
  
      if (isNaN(date)) {
          return false;
      }
  
      var comp = text.split('/');
  
      if (comp.length !== 3) {
          return false;
      }
  
      var m = parseInt(comp[0], 10);
      var d = parseInt(comp[1], 10);
      var y = parseInt(comp[2], 10);
      var date = new Date(y, m - 1, d);
      return (date.getFullYear() == y &amp;&amp; date.getMonth() + 1 == m &amp;&amp; date.getDate() == d);
  }
  </code></pre>