Restrict an Input field to only Letters in React

avatar

Borislav Hadzhiev

Last updated: Apr 28, 2022

banner

Check out my new book

Restrict an Input field to only Letters in React #

To restrict an input field to only letters in React.js:

  1. Set the type of the input field to text.
  2. Add an onChange event handler that removes all characters but letters.
  3. Keep the input value in a state variable.
App.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleChange = event => { const result = event.target.value.replace(/[^a-z]/gi, ''); setMessage(result); }; return ( <div> <div>123 hello 456 world</div> <input id="message" name="message" type="text" value={message} onChange={handleChange} /> </div> ); }; export default App;

react only letters input

We used the useState hook to keep track of the input field's value.

Every time the input's value is changed, the handleChange function is invoked.

We passed the following 2 parameters to the String.replace method to remove all non-letters.

NameDescription
regexpa regular expression we want to match in the string
replacementthe replacement for each match

The forward slashes / / mark the beginning of the regular expression.

The square brackets [] are called a character class. In our character class, we match all non letters.

When used inside of the square brackets [], a caret ^ symbol means "not the following". It's basically a negated match.

In the example, we replace all non letters with an empty string.

We used the g (global) flag because we want to match all occurrences of non letters in the string.

The i flag allows us to match all letters in a case insensitive manner.

If you need a regex cheatsheet, check out this one from MDN. It's by far the best one out there.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.