Categories
JavaScript Answers

How to force input to only allow alphabet letters with JavaScript?

Spread the love

Sometimes, we want to force input to only allow alphabet letters with JavaScript.

In this article, we’ll look at how to force input to only allow alphabet letters with JavaScript.

How to force input to only allow alphabet letters with JavaScript?

To force input to only allow alphabet letters with JavaScript, we can set the keypress event handler of the input to a function that returns whether the key that’s pressed is a alphabet key.

For instance, we write:

<input>

to add an input.

Then we write:

const input = document.querySelector('input')
input.onkeypress = () => {
  return /[a-z]/i.test(event.key)
}

We get the input with document.querySelector.

Then we set the input.onkeypress property to a function that returns /[a-z]/i.test(event.key).

event.key has the character of the key that’s pressed.

So we’re check whether the key pressed is an alphabet key with test.

Conclusion

To force input to only allow alphabet letters with JavaScript, we can set the keypress event handler of the input to a function that returns whether the key that’s pressed is a alphabet key.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *