screen_rotation
Copied to Clipboard
<!DOCTYPE html> <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://cdn.jsdelivr.net/npm/@babel/standalone@7.14.6/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel" data-presets="env,react"> const { useState } = React; function App() { const [inputValue, setInputValue] = useState(""); const [errorMessage, setErrorMessage] = useState(""); const handleChange = (event) => { const value = event.target.value; // For this example, let's say we want to restrict special characters and spaces const sanitizedValue = value.replace(/[^\w\d]/g, ""); setInputValue(sanitizedValue); // Validate the input here and set the error message if necessary if (sanitizedValue !== value) { setErrorMessage("Special characters and spaces are not allowed."); } else { setErrorMessage(""); } }; return ( <div className="container"> <h3> React Js Restrict Special Character and Space in Input field </h3> <input type="text" value={inputValue} onChange={handleChange} /> {errorMessage && <div className="error">{errorMessage}</div>} </div> ); } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> .container { max-width: 500px; margin: 0 auto; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); font-family: Arial, sans-serif; } input { width: 100%; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 5px; outline: none; box-sizing: border-box; } .error { font-size: 14px; font-weight: bold; color: red; margin-top: 5px; } </style> </body> </html>