-
-
Save arth2o/8471150 to your computer and use it in GitHub Desktop.
/** | |
* 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; | |
} |
Why is a future year an invalid date? (m[1] > thisYear) ? If, for example you want to make an event for january 2015 and it's currently december 2014, this would be flagged as invalid. Perhaps this was for a specific case but in general, any future year should be a valid date.
@michaelsidler Thanks Michael (it looks was copy paste :))!
@afdil13 returned param ret is true or false and that's enough.
@percy3d it is a specific validation and there this parameter can't be higher then this year.
Modified little bit to give a more valid date
// DAY CHECK
if( (m[3].length < 2) || m[3] < 1 || ((["04","06","09","11"].indexOf(m[2]) > -1 && m[3] > 30 ) || m[3] > 31)){ret = false;}
// FEBRUARY CHECK
if( (m[2] == 2 && m[3] > 29) || (m[2] == 2 && m[3] > 28 && m[1]%4 != 0)){ret = false;}
It returned true even for 2017-02-31.
Corrected it
also add stop regex
var m = str.match(/(\d{4})-(\d{2})-(\d{2})$/);
because 2019-02-282 return true
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
thanks guys,
before end of function if not giving return true is that oke?