简体   繁体   中英

regex to match date in a string

i try to allow only number 01 (1) to 53) after / and after 2000 and over.... so i create a regex but it don't seem to work

on this web page: http://www.regular-expressions.info/javascriptexample.html i tried it and it work well... but when i test in on a web page

10/2010, 23/2000

function isValidDate(value, format){
     var isValid = true;

     try{
         var inputVal = $(this).val();
         var dateWWYYYYRegex = '^(0[1-9]|[1234][0-9]|5[0-3])[-/.](20)\d\d$';

         var reg=new RegExp(dateWWYYYYRegex);

         if(!reg.test(value)){
            isValid = false;
            alert("Invalid");
         }

     }
     catch(error){
         isValid = false;
    }

    return isValid;
}

You have to escape backslashes if you're going to make a regex from a string. I'd just use regex syntax, since it's a constant anyway:

var reg = /^(0[1-9]|[1234][0-9]|5[0-3])[-/.](20)\d\d$/;

The regular expression doesn't really make any sense, however. It's not clear what it should be, because your description is also confusing.

edit — OK now that I see what you're doing, that regex should work, I guess.

Why use regex for this task? I think it's the wrong tool for this task

Simply split the string by the slash delimiter, and then use numerical functions to check if the values are in the range you want.

function isValidWeekOfYear(value){
   var bits = value.split('/');
   if(parseInt(bits[1]) < 2000) { return false; } /* probably also want to do a maximum value here? */
   if(parseInt(bits[0]) < 1 || parseInt(bits[0]) > 53) { return false; }
   return true;
}

It might need a bit more validation than that, but that should be a good starting point for you. Much less processing overhead than a regex just to parse a couple of numbers (and easier to read too).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM