javascript regex validate years in range

后端 未结 8 1115
猫巷女王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:33

    Regex for Current Year(Dynamic) from 1995

    var current_year = new Date().getFullYear().toString().split("");
    var reg=new RegExp("^(199[5-9]|200[0-9]|[0-"+current_year[0]+"][0-"+current_year[1]+"][0-"+current_year[2]+"][0-"+current_year[3]+"])$");
    reg.test("1995");
    
    0 讨论(0)
  • 2021-02-13 20:43

    RegExp does not seem to be the right tool here. If you have the year values already isolated surely a simple comparison would work :

    if (+yr >= 1990 && +yr <= 2010)
    

    The +yr converts the string to a number

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