practical 5
practical 5
JavaScript checks the values of these fields to ensure they meet validation rules:
Empty Field Check: Ensures required fields are not left blank.
Pattern Matching: Uses regular expressions to validate formats, such as email addresses or
phone numbers.
Length Check: Ensures text or password fields meet minimum and maximum length
requirements.
Custom Conditions: Checks if values meet specific criteria, such as matching passwords.
We can prevent form submission by calling a validation function when the form’s onsubmit event
is triggered. If the function returns false, the form will not be submitted.
If a field fails validation, error messages can be shown near the field. This can be done by modifying
the textContent or innerHTML of elements meant to display errors.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Form Validation</title>
<script src="myscript.js">
</script>
</head>
<body>
<h2>Registration Form</h2>
<form onsubmit="return validateForm()">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>
<label for="age">Age:</label><br>
<input type="text" id="age" name="age"><br><br>
</body>
</html>
myscript.js
function validateForm() {
// Get the form elements
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var age = document.getElementById("age").value;
if (name == "") {
alert("Name must be filled out.");
return false;
}
if (email == "") {
alert("Email must be filled out.");
return false;
}
return true;
}