Allow only alphabets in the input field in React
📅February 8, 2022
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
- Min and Max length input validation in React
- Password and Confirm Password validation in React
- How to render HTML in React
- Conditionally add attributes to React components
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.
App.js
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 class="app">
<div class="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 class="form-control" placeholder="Allow only alphabets" value={txt} onchange={onInputChange}>
</div>
);
}
export default App;
Output:
Output - Allow only alphabets in the input field in React - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂