JavaScript Is-Valid-Date Function (Public Domain)
April 2016



Here’s a free (public domain) function I wrote in JavaScript, that tells you whether a date is valid or not:


//  isValidDate expects the input to be a string of the form MM/DD/YYYY (all ten characters).
//
//  Public domain functions by Darel Rex Finley, 2016.

function isValidDate(s) {
  return s.length==10
  &&     s.charAt(0)>='0' && s.charAt(0)<='9'
  &&     s.charAt(1)>='0' && s.charAt(1)<='9' && s.substring(0,2)>='01' && s.substring(0,2)<='12'
  &&     s.charAt(2)=='/'
  &&     s.charAt(3)>='0' && s.charAt(3)<='9'
  &&     s.charAt(4)>='0' && s.charAt(4)<='9' && s.substring(3,5)>='01' && s.substring(3,5)<='31'
  &&     s.charAt(5)=='/'
  &&     s.charAt(6)>='0' && s.charAt(6)<='9'
  &&     s.charAt(7)>='0' && s.charAt(7)<='9'
  &&     s.charAt(8)>='0' && s.charAt(8)<='9'
  &&     s.charAt(9)>='0' && s.charAt(9)<='9' && s.substring(6)>='1970'
  &&   ( s.substring(3,5)!='31' || s.substring(0,2)!='04' && s.substring(0,2)!='06' && s.substring(0,2)!='09' && s.substring(0,2)!='11')
  &&   ( s.substring(0,2)!='02'         //  it's not Feb, or
  ||     s.substring(3,5)<='28'         //  it's Feb but not past the 28th, or
  ||     s.substring(3,5)=='29'         //  it's Feb 29th but
  &&     mult4(s.substring(8))          //      the year is a multiple of 4 and
  &&    (s.substring(8)!='00'           //      the year is not a multiple of 100..
  ||     mult4(s.substring(6,8)))); }   //          ..or the year is a multiple of 400

function mult4(twoDigits) {
  var a=twoDigits.charAt(0), b=twoDigits.charAt(1);
  if (a=='0' || a=='2' || a=='4' || a=='6' || a=='8') return b=='0' || b=='4' || b=='8';
  return b=='2' || b=='6'; }


Back to Tutorials.