Validating a simple form using JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Student Details Form</title>
</head>
<body>
<h1>Student Details Form</h1>
<form id="studentForm" onsubmit="return validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" placeholder="Enter your name">
<br><br>
<label for="age">Age:</label>
<input type="number" id="age" placeholder="Enter your age">
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email">
<br><br>
<button type="submit">Submit</button>
</form>
<p id="error" style="color: red;"></p>
<script>
function validateForm() {
// Get form values
let name = document.getElementById("name").value.trim();
let age = document.getElementById("age").value.trim();
let email = document.getElementById("email").value.trim();
let error = document.getElementById("error");
// Clear previous error message
error.textContent = "";
// Validate name
if (name === "") {
error.textContent = "Name is required.";
return false;
}
// Validate age
if (age === "" || isNaN(age) || age <= 0) {
error.textContent = "Please enter a valid age.";
return false;
}
// Validate email
if (email === "" || !email.includes("@")) {
error.textContent = "Please enter a valid email address.";
return false;
}
// If all validations pass
alert("Form submitted successfully!");
return true;
}
</script>
</body>
</html>
Explanation:
HTML Form:
- Input Fields:
id="name"
: For entering the student’s name.id="age"
: For entering the student’s age.id="email"
: For entering the student’s email.
- Submit Button: The
onsubmit
attribute calls thevalidateForm()
function when the form is submitted.
- Input Fields:
JavaScript Validation:
- The
validateForm()
function is triggered on form submission. - It retrieves the values of the name, age, and email fields.
- Validation Rules:
- Name: Must not be empty.
- Age: Must be a positive number.
- Email: Must contain "@" (basic validation).
- If any validation fails, an error message is displayed, and the form is not submitted (
return false
). - If all validations pass, an alert is shown, and the form submission proceeds (
return true
).
- The
Error Display:
- A
<p>
element withid="error"
displays the first validation error in red.
- A
This ensures basic client-side validation before submitting the form
Comments
Post a Comment