Form validation in JavaScript¶
It ensures that users have filled out forms in the correct format. Here’s a basic example of how you can do form validation in JavaScript:
<!-- HTML -->
<form id="myForm">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
// JavaScript
document.getElementById('myForm').addEventListener('submit', function(event) {
// Prevent the form from being submitted
event.preventDefault();
// Get the email field
let email = document.getElementById('email');
// Simple validation for email format
let regex = /\S+@\S+\.\S+/;
if (!regex.test(email.value)) {
alert('Invalid email format');
return false;
}
// If validation passes, you can submit the form
alert('Form submitted successfully');
return true;
});
In this example, when the form is submitted, the event listener is triggered. The event.preventDefault() method is called to prevent the form from being submitted immediately. This allows the JavaScript code to validate the form fields first.
The email field is then retrieved, and a regular expression is used to check if the email is in a valid format. If the email is not valid, an alert is shown and the function returns false. If the email is valid, an alert is shown to indicate that the form has been submitted successfully, and the function returns true.
This is a very basic example. In a real-world application, you would likely have more fields to validate, and you might want to show the validation errors next to the relevant fields instead of using alerts. You might also want to use a more sophisticated regular expression for email validation, or use a library to handle email validation.