Partial matching a string against a regex

前端 未结 6 1770
梦毁少年i
梦毁少年i 2021-02-04 01:02

Suppose that I have this regular expression: /abcd/ Suppose that I wanna check the user input against that regex and disallow entering invalid characters in the input. When user

6条回答
  •  鱼传尺愫
    2021-02-04 01:43

    I think that you have to have 2 regex one for typing /a?b?c?d?/ and one for testing at end while paste or leaving input /abcd/

    This will test for valid phone number:

    const input = document.getElementById('input')
    
    let oldVal = ''
    input.addEventListener('keyup', e => {
      if (/^\d{0,3}-?\d{0,3}-?\d{0,3}$/.test(e.target.value)){
        oldVal = e.target.value
      } else {
        e.target.value = oldVal
      }
    })
    input.addEventListener('blur', e => {
      console.log(/^\d{3}-?\d{3}-?\d{3}-?$/.test(e.target.value) ? 'valid' : 'not valid')
    })

    And this is case for name surname

    const input = document.getElementById('input')
    
    let oldVal = ''
    input.addEventListener('keyup', e => {
      if (/^[A-Z]?[a-z]*\s*[A-Z]?[a-z]*$/.test(e.target.value)){
        oldVal = e.target.value
      } else {
        e.target.value = oldVal
      }
    })
    input.addEventListener('blur', e => {
      console.log(/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(e.target.value) ? 'valid' : 'not valid')
    })

提交回复
热议问题