javascript - Regex match should be 1 or 2 digit but not zero with single digit in date format -


var dateobj = {   '01/01/2017' : true,   '1/1/2016' : true,   '1/1/16' : true,   '1/1/116' : false,   '01/11/2016' : true,   '01.01.2016' : true,   '01.01_2016' : false,   '01-0-2016' : false,   '01-01-2016' : true }; var failedattempts = []; var date_val = "01/01/2017"; var re = /^(\d{1,2})[/.\-](\d{1,2})[/.\-](\d{4}|\d{2})$/; for(let in dateobj){   let result = re.test(i);   if(result != dateobj[i]){     failedattempts.push(i);   } } if(failedattempts.length > 0){   console.error('unit test fails');   console.log(failedattempts); }else{   console.log('unit test pass'); } 

'01-0-2016' : false consider case returns true in wrong format. want rewrite regex digit matches either 1 or 2 not 0 in single digit.

restrict digit matching patterns negative (?!0+\b) lookaheads:

 /^(?!0+\b)(\d{1,2})[\/.-](?!0+\b)(\d{1,2})[\/.-](\d{4}|\d{2})$/    ^^^^^^^^               ^^^^^^^^  

see regex demo

if needn't restrict both day month parts, remove unnecessary lookahead.

the (?!0+\b) pattern matches 1 or more zeros followed word boundary (that is, there cannot letter/digit/_ after it), , if pattern found, match failed.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -