JavaScript form validation ensures that users fill out a form correctly before submitting it. It can be used to check required fields, formats (like email addresses or phone numbers), and other constraints such as minimum or maximum values.
Here's a simple example of JavaScript validation:
Getting Started
The following are examples of web form validation in JavaScript, which includes three fields to validate before submitting the form: first name, email, and age. Each field has a corresponding error message span element, which will display the error text if the validation fails.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Example</title>
<style>
.error { color: red; font-size: 12px; }
</style>
</head>
<body>
<h2>Registration Form</h2>
<form id="myForm" name="myForm" onsubmit="return validateForm()">
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname">
<span id="fnameError" class="error"></span><br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<span id="emailError" class="error"></span><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age">
<span id="ageError" class="error"></span><br><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
// Clear previous error messages
document.getElementById("fnameError").innerText = "";
document.getElementById("emailError").innerText = "";
document.getElementById("ageError").innerText = "";
let isValid = true;
// Get form values
const fname = document.forms["myForm"]["fname"].value;
const email = document.forms["myForm"]["email"].value;
const age = document.forms["myForm"]["age"].value;
// Validate First Name
if (fname === "") {
document.getElementById("fnameError").innerText = "First name is required.";
isValid = false;
}
// Validate Email
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (email === "") {
document.getElementById("emailError").innerText = "Email is required.";
isValid = false;
} else if (!email.match(emailPattern)) {
document.getElementById("emailError").innerText = "Please enter a valid email address.";
isValid = false;
}
// Validate Age
if (age === "" || age < 18 || age > 100) {
document.getElementById("ageError").innerText = "Please enter a valid age between 18 and 100.";
isValid = false;
}
return isValid;
}
</script>
</body>
</html>
Basic Form Validation Using Javascript
Explanation:
- Form Structure:
- The form has three fields:
First Name
,Email
, andAge
. - Each field has a corresponding error message span element, which will display the error text if the validation fails.
- The form has three fields:
- JavaScript Function (validateForm):
- The
validateForm()
function is called when the form is submitted (onsubmit="return validateForm()"
). - It checks the values entered by the user for each field and performs the following validations:
- First Name: Must not be empty.
- Email: Must not be empty and must match a regular expression for a valid email format.
- Age: Must be between 18 and 100.
- The
- Error Handling:
- If a field is invalid, an error message is displayed next to the field, and the form will not be submitted (
return false
). - If all fields are valid, the form is submitted (
return true
).
- If a field is invalid, an error message is displayed next to the field, and the form will not be submitted (
Customizing the Validation:
You can modify this validation code based on your specific needs, such as adding more fields, using different validation rules (like minimum length for text fields), or validating other formats (like phone numbers or dates).
Best Practices:
- Client-side validation improves user experience by giving immediate feedback.
- Server-side validation is essential to protect against invalid or malicious data, even if JavaScript validation passes.
Summary
In this post, we learned client side form validation using javascript. The javascript form validation is as easy other programing logic. I hope you have enjoyed it.
Thanks