<html>
<head>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const { useState } = React;
function App() {
const [urlValue, setUrlValue] = useState('');
const [isValidUrl, setIsValidUrl] = useState(true);
const [errorMessage, setErrorMessage] = useState('');
const handleChange = (event) => {
setUrlValue(event.target.value);
setIsValidUrl(true);
setErrorMessage('');
}
const handleSubmit = (event) => {
event.preventDefault();
// URL validation using regular expressions
const urlPattern = /^(http[s]?:\/\/)(www\.)?[^\s$.?#].[^\s]*$/;
if (urlPattern.test(urlValue)) {
setIsValidUrl(true);
alert(urlValue); // Perform any necessary actions with the valid URL
} else {
setIsValidUrl(false);
setErrorMessage('Please enter a valid URL.');
}
}
return (
<div className='container'>
<form onSubmit={handleSubmit}>
<label>
URL:
<input
type="text"
value={urlValue}
onChange={handleChange}
className={!isValidUrl ? 'invalid' : ''}
/>
</label>
{!isValidUrl && <p className="error-message">{errorMessage}</p>}
<button type="submit">Submit</button>
</form>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
* {
box-sizing: border-box;
}
.container {
margin: 0 auto;
width: 600px;
text-align: center;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24);
padding: 20px;
}
form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 20px;
}
label {
display: flex;
flex-direction: column;
align-items: flex-start;
margin-bottom: 10px;
}
input[type="text"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 300px;
}
.invalid {
border-color: red;
}
.error-message {
color: red;
margin-top: 5px;
}
button[type="submit"] {
padding: 8px 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button[type="submit"]:hover {
background-color: #45a049;
}
</style>
</body>
</html>
``