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,211
  • 1
  • 11
  • 27

4 Answers4

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,'')">
Eaten by a Grue
  • 19,208
  • 10
  • 77
  • 99
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
  • 462
  • 4
  • 14
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,211
  • 1
  • 11
  • 27
-1

Your solution is only looking at one character.

It looks like you just want to filter out any characters that don't meet the criteria. In that case you can use the array filter method like so:

const regex = /[A-Za-z]/;

function validate(e) {
    const chars = e.target.value.split('');
    e.target.value = chars.filter(function(char) {
        return regex.test(char);
    }).join('');
}

document.querySelector('#inputTextBox').addEventListener('input', validate);
Jack A.
  • 3,768
  • 1
  • 20
  • 27
  • 1
    why reinvent a simple reg exp? – epascarello Jul 20 '20 at 14:00
  • @epascarello Not sure what you mean. Are you referring to the regex `replace` solution linked in one of the comments? There are many ways to solve any given problem. This isn't necessarily the "best" solution, but the core problem with the original solution was one vs. many, and this solution shows how to address that. – Jack A. Jul 20 '20 at 15:05