Accept all numbers except 5 consecutive zeros : Javascript

前端 未结 4 613
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 17:54

I want to validate a 5 digit number which should not be 00000. All numbers except 00000 are allowed.

examples : 01201 , 00001, 21436 , 45645 are valid numbers and 1,

相关标签:
4条回答
  • 2021-01-06 18:41

    Using negative positive lookahead:

    /^(?!0{5})\d{5}$/
    

    /^(?!0{5})\d{5}$/.test('01201')
    // => true
    /^(?!0{5})\d{5}$/.test('00001')
    // => true
    /^(?!0{5})\d{5}$/.test('21436')
    // => true
    /^(?!0{5})\d{5}$/.test('1')
    // => false
    /^(?!0{5})\d{5}$/.test('12')
    // => false
    /^(?!0{5})\d{5}$/.test('00000')
    // => false
    
    0 讨论(0)
  • 2021-01-06 18:45

    No need for negative lookahead

    Live Demo

    function isvalid5(str) {
      return str != "00000" && /^\d{5}$/.test(str);
    }
    
    0 讨论(0)
  • 2021-01-06 18:46

    for regex engines that do not support lookahead:

    ^(0000[1-9]|000[1-9][0-9]|00[1-9][0-9]{2}|0[1-9][0-9]{3}|[1-9][0-9]{4})$
    
    0 讨论(0)
  • 2021-01-06 18:49

    You can use a negative look ahead:

    ^(?!0{5})\d{5}$
    

    The negative loo ahead (?!...) will fail the whole regex if what's inside it matches, \d is a shortcut for [0-9].

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