Form Validation Code Using | HTML CSS and JS
here's a simple example of HTML and CSS for form validation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
max-width: 400px;
margin: 0 auto;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"],
input[type="email"],
input[type="password"],
input[type="tel"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
}
.error-message {
color: red;
font-size: 0.8em;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>Form Validation</h2>
<form id="myForm" action="#" method="post" onsubmit="return validateForm()">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<div id="name-error" class="error-message"></div>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<div id="email-error" class="error-message"></div>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="password-error" class="error-message"></div>
</div>
<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone">
<div id="phone-error" class="error-message"></div>
</div>
<input type="submit" value="Submit">
</form>
</div>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var phone = document.getElementById('phone').value;
var isValid = true;
// Name validation
if (name.trim() === '') {
document.getElementById('name-error').innerHTML = 'Name is required';
isValid = false;
} else {
document.getElementById('name-error').innerHTML = '';
}
// Email validation
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
document.getElementById('email-error').innerHTML = 'Invalid email format';
isValid = false;
} else {
document.getElementById('email-error').innerHTML = '';
}
// Password validation
if (password.trim() === '') {
document.getElementById('password-error').innerHTML = 'Password is required';
isValid = false;
} else {
document.getElementById('password-error').innerHTML = '';
}
// Phone number validation
var phonePattern = /^\d{10}$/;
if (!phonePattern.test(phone)) {
document.getElementById('phone-error').innerHTML = 'Invalid phone number';
isValid = false;
} else {
document.getElementById('phone-error').innerHTML = '';
}
return isValid;
}
</script>
</body>
</html>
No comments: