Skip to content

Instantly share code, notes, and snippets.

@arth2o
Last active September 30, 2020 11:27
Show Gist options
  • Save arth2o/8471150 to your computer and use it in GitHub Desktop.
Save arth2o/8471150 to your computer and use it in GitHub Desktop.
Javascript function: validate date (yyyy-mm-dd) format via JavaScript.
/**
* isValidDate(str)
* @param string str value yyyy-mm-dd
* @return boolean true or false
* IF date is valid return true
*/
function isValidDate(str){
// STRING FORMAT yyyy-mm-dd
if(str=="" || str==null){return false;}
// m[1] is year 'YYYY' * m[2] is month 'MM' * m[3] is day 'DD'
var m = str.match(/(\d{4})-(\d{2})-(\d{2})/);
// STR IS NOT FIT m IS NOT OBJECT
if( m === null || typeof m !== 'object'){return false;}
// CHECK m TYPE
if (typeof m !== 'object' && m !== null && m.size!==3){return false;}
var ret = true; //RETURN VALUE
var thisYear = new Date().getFullYear(); //YEAR NOW
var minYear = 1999; //MIN YEAR
// YEAR CHECK
if( (m[1].length < 4) || m[1] < minYear || m[1] > thisYear){ret = false;}
// MONTH CHECK
if( (m[2].length < 2) || m[2] < 1 || m[2] > 12){ret = false;}
// DAY CHECK
if( (m[3].length < 2) || m[3] < 1 || m[3] > 31){ret = false;}
return ret;
}
@blackbone23
Copy link

blackbone23 commented Sep 30, 2020

also add stop regex
var m = str.match(/(\d{4})-(\d{2})-(\d{2})$/);

because 2019-02-282 return true

if we just want to check the format, this is the correct way to do it. i can use it in my vuelidate custom checker

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment