<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 [ipAddress, setIPAddress] = useState('');
const [isValid, setIsValid] = useState(true);
const handleChange = (event) => {
setIPAddress(event.target.value);
setIsValid(true);
};
const handleSubmit = (event) => {
event.preventDefault();
// Regular expression to validate IP address
const ipRegex = /^([0-9]{1,3}\.){3}[0-9]{1,3}$/;
if (!ipRegex.test(ipAddress)) {
setIsValid(false);
return;
}
// IP address is valid
// Do something with the valid IP address
alert('Valid IP address: ' + ipAddress);
};
return (
<div className='container'>
<h3>React Js Validate Ip Address</h3>
<form onSubmit={handleSubmit}>
<label>
IP Address:
<input type="text" value={ipAddress} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
{!isValid && <p style={{ color: 'red' }}>Invalid IP address</p>}
</form>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
* {
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
margin: 0 auto;
width: 600px;
padding: 20px;
display: flex;
align-items: center;
flex-direction: column
}
h3 {
text-align: center;
margin-bottom: 20px;
}
form {
display: flex;
flex-direction: column;
align-items: center;
}
label {
margin-bottom: 10px;
}
input[type="text"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 100%;
}
button[type="submit"] {
padding: 8px 16px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-top: 10px;
}
button[type="submit"]:hover {
background-color: #45a049;
}
p {
margin-top: 10px;
font-size: 14px;
}
</style>
</body>
</html>