<html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const { useState } = React;
function App() {
const [numericInput, setNumericInput] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const filterNonNumeric = (e) => {
// Replace non-numeric characters with an empty string
let input = e.target.value.replace(/[^0-9]/g, "");
if (input !== e.target.value) {
// Input was invalid, set error message
setErrorMessage("Only numeric characters are allowed.");
} else {
// Input was valid, clear error message
setErrorMessage("");
}
setNumericInput(input);
};
return (
<div>
<h3>React Js Text Input allow Only Number</h3>
<input
type="text"
value={numericInput}
onChange={filterNonNumeric}
/>
{errorMessage && <div style={{ color: "red" }}>{errorMessage}</div>}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
div {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 20px;
}
h3 {
font-size: 24px;
font-weight: bold;
margin-bottom: 10px;
}
input {
padding: 12px 16px;
font-size: 18px;
border: 2px solid #ddd;
border-radius: 8px;
background-color: #f8f8f8;
color: #333;
transition: border-color 0.2s ease-in-out;
width: 100%;
max-width: 400px;
}
input:focus {
outline: none;
border-color: #0077cc;
box-shadow: 0 0 0 3px rgba(0, 119, 204, 0.3);
}
div>div {
margin-top: 10px;
}
</style>
</body>
</html>