0

I need to make my input text just accept English letter without spaces or number or can copy and paste in it!

I have tried this code and it works but when I copy and paste anything outside input it accept the value:

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('');
    }
}

document.querySelector('#inputTextBox').addEventListener('input', validate);

How can I make it not allow to copy and paste value out of input?

feel free to use Jquery or pure JS

Greedo
  • 3,438
  • 1
  • 13
  • 28

3 Answers3

3

You can use oninput event with replace to restrict input like this:

<input type="text" oninput="this.value=this.value.replace(/[^a-z]/gi,'')">
0

You need to look at paste event.

So in order to prevent user from pasting anything which is not allowed

document.querySelector('#inputTextBox').addEventListener('paste', validate);

You may reset the value of input after validating.

HARDY8118
  • 622
  • 7
  • 15
0

The loop is not really necessary, you can use match

function validate(e) {
    e.target.value = e.target.value.match(/[A-Za-z]/g).join('');
}

document.querySelector('#inputTextBox').addEventListener('input', validate);
<input id="inputTextBox"/>
Greedo
  • 3,438
  • 1
  • 13
  • 28