javascript regex validate years in range

后端 未结 8 1114
猫巷女王i
猫巷女王i 2021-02-13 20:11

I have input field for year and I need a regex for validation it. I have such code: ^([12]\\d)?(\\d\\d)$. But I want allow to validate only years in certain range (

相关标签:
8条回答
  • 2021-02-13 20:18

    Try this:

    1990 - 2010:

    /^(199\d|200\d|2010)$/
    

    1950 - 2050:

    /^(19[5-9]\d|20[0-4]\d|2050)$/
    

    Other examples:

    1945 - 2013:

    /^(194[5-9]|19[5-9]\d|200\d|201[0-3])$/
    

    1812 - 3048:

    /^(181[2-9]|18[2-9]\d|19\d\d|2\d{3}|30[0-3]\d|304[0-8])$/
    

    Basically, you need to split your range into easy "regexable" chunks:

    1812-3048: 1812-1819 + 1820-1899 + 1900-1999 + 2000-2999 + 3000-3039 + 3040-3048
        regex: 181[2-9]    18[2-9]\d   19\d\d      2\d{3}      30[0-3]\d   304[0-8]
    
    0 讨论(0)
  • 2021-02-13 20:18

    Regex:

    /^(19[5-9]\d|20[0-4]\d|2050)$/
    

    Easier...

    var year = parseInt(textField.value, 10);
    if( year >= 1950 && year <= 2050 ) {
        ...
    }
    
    0 讨论(0)
  • 2021-02-13 20:19

    if you want to check for age between for example 18 or 70 I did it like this. my solution was

    function yearRange(year) {
      let now = new Date().getFullYear();
      let age = now - Number(year);
      if (age < 18 || age > 70) return false;
      return true;
    }
    
    0 讨论(0)
  • 2021-02-13 20:30

    Here is a regex if you want to find a year in a film name for example. Years b/n 1900 - 2029 and some symbols are allowed wrapping the year .-_+[(

    (?<=(?:\s|\.|_|\-|\+|\(|\[))(?:19[2-9]|20[0-2])\d(?=\s|$|\.|_|\-|\+|\)|\])
    

    check it out here https://regex101.com/r/eQ9zK7/82

    Note you can not start with year, because there is at least interval in front. In the example first few lines are matching, because we have multiple lines in a single line they wont match.

    1917.2019.1080p... even if 1917 was in range it will mark only 2019

    0 讨论(0)
  • 2021-02-13 20:31

    For a range from 1950 to 2050 you may use the following regex:

    ^19[5-9]\d|20[0-4]\d|2050$
    

    Online demo

    0 讨论(0)
  • 2021-02-13 20:32
    (199[0-9]|200[0-9]|2010)
    

    This will work in your 'example case'.

    Helpful website: http://utilitymill.com/utility/Regex_For_Range

    0 讨论(0)
提交回复
热议问题