/**
* Make sure that the passed value is valid for the proposed condition. If
* isRequired is true, dateString must not be blank or null as well as being
* a valid date string. If isRequired is false, dateString may be blank or null,
* but when it's not, it must be a valid date string. A valid date string looks
* like YYYY-MM-DD
*
* @param dateString {String}
* @param isRequired {Boolean}
* @returns {Boolean}
*/
function isDateValid( dateString, isRequired ) {
var regex = /^\d\d\d\d-\d\d-\d\d$/ ;
var retVal = true ;
if ( ! isRequired ) {
if ( ( null == dateString ) || ( '' == dateString ) ) {
return true ;
}
}
else {
retVal = ( ( null !== dateString ) && ( '' !== dateString ) ) ;
}
retVal = ( retVal && ( null !== dateString.match( regex ) ) ) ;
if ( retVal ) {
var daysInMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] ;
var yr = parseInt( dateString.substring( 0, 4 ) ) ;
var mo = parseInt( dateString.substring( 5, 7 ) ) ;
var da = parseInt( dateString.substring( 8, 10 ) ) ;
if ( ( yr % 4 ) && ( ( yr % 400 ) || ! ( yr % 100 ) ) ) {
daysInMonths[ 1 ]++ ; // Leap day!
}
if ( ( yr < 2000 ) || ( yr > 2038 )
|| ( mo < 1 ) || ( mo > 12 )
|| ( da < 1 ) || ( da > daysInMonths[ mo ] )
) {
retVal = false ;
}
}
return ( retVal ) ;
}
If you know of a more efficient way to handle a MySQL (YYYY-DD-MM) date validation, please reply to this post. :-)
Tuesday, August 2, 2016
Efficient MySQL Date Verification in Javascript?
I'm not the best person I know at determining what is efficient in JavaScript (ECMAScript) though I would like to think that this could help someone.
Subscribe to:
Comments (Atom)