Allow only alphabets in the input field in React
In this article, we will teach you how to allow only alphabets in the input field in React. Here, we will implement this functionality without the React package.
Checkout more articles on ReactJS
Here, we have to use the Regular Expression inside the onChange
event of the input field to allow only alphabets. We will only set the value when it matches the condition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import React, { useState } from 'react'; function App() { const [txt, setTxt] = useState(''); const onInputChange = e => { const { value } = e.target; console.log('Input value: ', value); const re = /^[A-Za-z]+$/; if (value === "" || re.test(value)) { setTxt(value); } } return ( <div className="app"> <div className='mb-3'><strong>Allow only alphabets in the input field in React - <a href="https://www.cluemediator.com" target="_blank" rel="noreferrer noopener">Clue Mediator</a></strong></div> <input className='form-control' placeholder='Allow only alphabets' value={txt} onChange={onInputChange} /> </div> ); } export default App; |
Output:
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂
But is is also not taking space
It will only accept alphabets and not spaces or other special characters.