javascript - How to allow regex to work for mm/dd/yyyy and yyyy-mm-dd format -


my regex mm/dd/yyyy is:

/^((0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/](19|20)[0-9]{2})*$/ 

i want use mm/dd/yyyy , yyyy-mm-dd both format.

i tried below 1 don't want user type in number date , month.

/^((\d{4})-(\d{2})-(\d{2})|(\d{2})\/(\d{2})\/(\d{4}))$/ 

i tried below make work not sure wrong here:

/^((0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/](19|20)[0-9]{2})|((19|20)[0-9]{2})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])*$/ 

the below gives function produces parser format 1 describe. dateparser('yyyy/mm/dd')('1990-03-25') { y: 1990, m: 3, d: 25 }.

you can use chain function chain([dateparser('mm/dd/yyyy'), dateparser('yyyy-mm-dd')])('2014-04-04') try formats in order.

var patterns = {   yyyy: '\\d{4}',   yy:   '\\d{2}',   mm:   '0\\d|1[012]',   m:    '0?\\d|1[012]',   dd:   '[3][01]|[012]\\d',   d:    '[3][01]|[012]?\\d',   hh:   '[2][0-4]|[01][0-9]',   h:    '[2][0-4]|[01]?[0-9]',   hh:   '[1][0-2]|0\\d',   h:    '[1][0-2]|0?\\d',   mm:   '[0-5]\\d',   m:    '[0-5]?\\d',   ss:   '[0-5]\\d',   s:    '[0-5]?\\d' }  function dateparser(pattern) {   var grouptofieldnames = [null];   var regexpattern = pattern.replace(       /([a-za-z]+)|[.?+*\[\]\(\)\{\}^$\|\\]/g,       function (m, field, punc) {         if (patterns.hasownproperty(field)) {           grouptofieldnames.push(field[0]);           return '(' + patterns[field] + ')';         } else if (punc) {           return '\\' + punc;         } else {           return m;         }       });   var regex = new regexp('^' + regexpattern + '$');   return function (datestring) {     var match = datestring.match(regex);     if (match) {       var fields = {};       (var = 1, n = grouptofieldnames.length; < n; ++i) {         fields[grouptofieldnames[i]] = parseint(match[i], 10);       }       return fields;     }   }; }  function chain(parsers) {   var arr = parsers.slice(0);   return function (x) {     (var = 0, n = arr.length; < n; ++i) {       var result = (0,arr[i])(x);       if (result) { return result; }     }   }; }  console.log(json.stringify(     dateparser('yyyy/mm/dd h:mm:ss')('2014/12/31 7:30:25') ));  console.log(json.stringify(     chain([dateparser('mm/dd/yyyy'), dateparser('yyyy-mm-dd')])     ('2014-04-04') )); 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -