Form enhancement and validation
A form can be enhanced by styling, having placeholders, validation of input and submitting the form only when all inputs are in order.<!DOCTYPE html>
<html>
<head>
<title>Simple Form</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h3>Simple Form</h3>
<form id="myForm">
Name: <input type="text" id="name" placeholder=”type name”><br>
<span id="nameError" class="error"></span><br>
Email: <input type="text" id="email" placeholder=”type email”><br>
<span id="emailError" class="error"></span><br>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
e.preventDefault(); // stop form from submitting
// Clear previous errors
document.getElementById('nameError').textContent = ' ';
document.getElementById('emailError').textContent = ' ';
// Get values
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
let valid = true;
// Check name
if (name.trim() === ' ') {
document.getElementById('nameError').textContent = 'Name is required';
valid = false;
}
// Basic email check (just '@' and '.')
if (email.indexOf('@') === -1 || email.indexOf('.') === -1) {
document.getElementById('emailError').textContent = 'Invalid email';
valid = false;
}
if (valid) {
alert('Form submitted');
}
});
</script>
</body>
</html>
No comments:
Post a Comment