In this blog we will see how we can validate our HTML form with the help of html attributes and JavaScript. If you are beginner than don't get scared of this JavaScript code. In future when we deep dive to JavaScript lessons you will easily understand what we are doing for validating our form.
HTML CODE FOR FORM VALIDATION
<form id="registrationForm"> <label for="username">Username</label> <input type="text" id="username" name="username" required> <label for="email">Email</label> <input type="email" type="email" id="email" name="email" required> <label for="password">Password</label> <type="password" id="password" name="password" required> </form>
In this form:
- The
required
attribute is added to each input field, ensuring that they cannot be submitted empty. - The
type="email"
attribute on the email input field ensures that the browser will validate the input to make sure it's a valid email address.
However, for more complex validation, such as ensuring that the password meets certain criteria or checking if a username is already taken, we can use JavaScript.
JAVASCRIPT CODE FOR FORM VALIDATION
<script> document.getElementById('registrationForm').addEventListener('submit', function(event) { var username = document.getElementById('username').value; var email = document.getElementById('email').value; var password = document.getElementById('password').value; // Custom validation for username (minimum length) if (username.length < 5) { alert('Username must be at least 5 characters long.'); event.preventDefault(); // Prevent form submission return; } // Custom validation for password (minimum length) if (password.length < 8) { alert('Password must be at least 8 characters long.'); event.preventDefault(); // Prevent form submission return; } // Custom validation for email format using regular expression var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(email)) { alert('Please enter a valid email address.'); event.preventDefault(); // Prevent form submission return; } // If all validation passes, form submission continues }); </script>
In this JavaScript code:
- We listen for the form's
submit
event. - We retrieve the values entered by the user for username, email, and password.
- We perform custom validation, such as checking the length of the username and password, and using a regular expression to validate the email format.
- If any validation fails, we prevent the form from being submitted by calling
event.preventDefault()
, and display an alert message to the user.
This way, we ensure that the form data submitted is valid and meets our specific criteria.