Skip to content

Instantly share code, notes, and snippets.

@SkyNaris
Created May 13, 2025 16:55
Show Gist options
  • Save SkyNaris/bfda219fb95760d56b90cca49590adac to your computer and use it in GitHub Desktop.
Save SkyNaris/bfda219fb95760d56b90cca49590adac to your computer and use it in GitHub Desktop.
<!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;
max-width: 500px;
margin: 0 auto;
padding: 20px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input {
width: 100%;
padding: 8px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #45a049;
}
.error {
color: red;
font-size: 14px;
margin-top: 5px;
}
</style>
</head>
<body>
<h1>Registration Form</h1>
<form id="myForm">
<div class="form-group">
<label for="name">Name*:</label>
<input type="text" id="name" name="name">
<div id="nameError" class="error"></div>
</div>
<div class="form-group">
<label for="email">Email*:</label>
<input type="text" id="email" name="email">
<div id="emailError" class="error"></div>
</div>
<div class="form-group">
<label for="age">Age:</label>
<input type="number" id="age" name="age">
<div id="ageError" class="error"></div>
</div>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
// Prevent form submission
event.preventDefault();
// Get form values
const name = document.getElementById('name').value.trim();
const email = document.getElementById('email').value.trim();
const age = document.getElementById('age').value.trim();
// Reset error messages
document.getElementById('nameError').textContent = '';
document.getElementById('emailError').textContent = '';
document.getElementById('ageError').textContent = '';
let isValid = true;
// Validate name
if (name === '') {
document.getElementById('nameError').textContent = 'Name is required';
isValid = false;
}
// Validate email
if (email === '') {
document.getElementById('emailError').textContent = 'Email is required';
isValid = false;
} else if (!email.includes('@')) {
document.getElementById('emailError').textContent = 'Email must contain @';
isValid = false;
}
// Validate age
if (age !== '') {
const ageNum = Number(age);
if (isNaN(ageNum) || ageNum <= 0) {
document.getElementById('ageError').textContent = 'Age must be a number greater than 0';
isValid = false;
}
}
// If all valid, show success message
if (isValid) {
alert('Form submitted!');
// You could also submit the form to a server here with:
// this.submit();
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment