How to allow only English letters in input fields?

前端 未结 4 1669
无人及你
无人及你 2021-01-14 17:30

So, this is my input field:


How can I allow only English letters?

This is the RegEx

4条回答
  •  死守一世寂寞
    2021-01-14 17:33

    You could use /[A-Za-z]/ regular expression and an input event handler which is fired every time the value of the element changes. Something like below:

    const regex = /[A-Za-z]/;
    function validate(e) {
      const chars = e.target.value.split('');
      const char = chars.pop();
      if (!regex.test(char)) {
        e.target.value = chars.join('');
        console.log(`${char} is not a valid character.`);
      }
    }
    document.querySelector('#myInput').addEventListener('input', validate);
    
    

提交回复
热议问题