In the first part of this series, we discussed HTML form validation using built-in HTML5 attributes. While using HTML5 attributes is a simple and effective way to perform form validation, it has some limitations. For example, it only works in modern browsers that support HTML5 and doesn't allow for complex validation rules.
This blog post will discuss how to perform form validation using JavaScript. You can go ahead and grab the starter files if you would love to code along.
Prerequisites
This tutorial assumes that you have a basic knowledge of HTML and JavaScript.
Why Use JavaScript for Form Validation
Although HTML5 attributes offer a basic level of form validation, utilizing JavaScript for form validation offers various advantages compared to relying solely on HTML5 attributes:
Better custom validation: With JavaScript, you can implement custom validation rules that go beyond what HTML5 attributes offer. JavaScript allows you to validate input in unique ways that match your specific needs. You can create custom validation functions to check for specific formats, compare values between fields, and perform other complex validation checks.
More control: HTML5 form validation attributes limit you to predefined validation types. JavaScript gives you greater control over the form validation process. You can define the validation rules, error messages, and feedback mechanisms, and can control how the form behaves based on the validation result.
Cross-browser compatibility: HTML5 form validation attributes may behave differently across different browsers. With JavaScript, you can ensure that your validation works consistently across all browsers.
Form Validation Using JavaScript
There are a couple of steps we need to take to be able to validate our form with JavaScript:
Access form elements.
Add event listeners to the form and/or form elements.
Create custom validation functions
Display error message.
Access Form Elements
Accessing form elements is an important step in validating a form using JavaScript. We can use the document object's method, getElementById
, to access form elements. getElementById
method allows us to access a form element by its unique id
attribute. Consider our name
input field:
<div>
<label for="password">Password</label>
<input type="password" id="password" name="password" />
</div>
We can access the name
input field with the getElementById
method like so:
const passwordInput = document.getElementById("password");
We can also access the form elements by using form.elements
. form.elements
returns all the form control contained in an element. You can access a form control by using its name
or index
:
const form = document.getElementById("form");
const { name, email, password } = form.elements;
We can start our validation once we have access to our input fields.
Add Event Listeners to the Form or Form Elements
JavaScript provides several methods we can use to validate our form. Some of these events include:
submit
: triggers when the form is submittedinput
: triggers when the value of an input element changeschange
: triggers when the value of an element(select
element included) changesfocus
: triggers when an element is focusedblur
: triggers when an element loses focus
The choice of which event to use depends on your specific needs and the type of feedback you want to provide to the user. Let’s add submit
event to our form and input
event to our password.
// access elements
const passwordInput = document.getElementById("password");
const form = document.getElementById("form");
// add event listeners
passwordInput.addEventListener("input", (e) => {
console.log("Password changed");
});
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("form submitted");
});
💡
e.preventDefault()
will prevent our form from being submitted.
Create Custom Validation Functions
JavaScript provides a powerful set of tools for validating form data. We can:
use regular expressions to validate input patterns, e.g email patterns.
compare values against other fields, e.g password and confirm password.
make AJAX request to check an input field, e.g check if a username is unique.
Let’s go ahead and make sure that the user’s password is at least 6 characters
// access elements
// ...
const validatePassword = (password) => password.length > 5;
passwordInput.addEventListener("input", (e) => {
// update our event listener
const { value } = e.target;
const isValid = validatePassword(value);
console.log(isValid);
});
Let’s also make sure that the name
field is not empty before submitting the form:
// other code
// .....
const validateName = (name) => name.length > 0;
form.addEventListener("submit", (e) => {
e.preventDefault();
const { name } = e.target.elements;
const isNameValid = validateName(name.value);
if (!isNameValid) {
console.log("Please enter a valid name");
return;
}
console.log("submitted");
});
Enter a name and password to test the current implementation. However, there is an issue with the code as it still allows the user to submit the form without entering a password. This occurs because the password is only validated when it's changed, rather than when the user changes the password and attempts to submit the form.
Let’s validate the password too when the user tries to submit the form:
// other code
// .....
const validateName = (name) => name.length > 0;
form.addEventListener("submit", (e) => {
e.preventDefault();
const { name, password } = e.target.elements;
const isNameValid = validateName(name.value);
const isPasswordValid = validatePassword(password.value);
if (!isNameValid) {
console.log("Please enter a valid name");
return;
}
if (!isPasswordValid) {
console.log("Please enter a valid password");
return;
}
console.log("submitted");
});
💡 I’m sure you still noticed that a user can submit the form even without an
Display Error Messages
One of the main reasons for creating a custom validation is to be able to display custom error messages. As seen in the earlier HTML validation constraint examples, whenever a user attempts to submit an invalid form, the browser shows an error message. However, there's no standard method to alter their appearance using CSS.
Let’s go ahead and create a custom error message for our input fields:
// other code
const passwordError = document.getElementById("passwordError");
const nameError = document.getElementById("nameError");
passwordInput.addEventListener("input", (e) => {
const { value } = e.target;
const isValid = validatePassword(value);
if (isValid) {
passwordError.textContent = "";
} else {
passwordError.textContent = "Password must be longer than 5 characters";
}
});
form.addEventListener("submit", (e) => {
e.preventDefault();
const { name, password } = e.target.elements;
const isNameValid = validateName(name.value);
const isPasswordValid = validatePassword(password.value);
if (!isNameValid) {
nameError.textContent = "Name must not be empty";
return;
} else {
nameError.textContent = "";
}
if (!isPasswordValid) {
passwordError.textContent = "Password must be longer than 5 characters";
return;
} else {
passwordError.textContent = "";
}
console.log("Submitted");
});
💡 Some basic CSS has been applied to our error message.
Conclusion
JavaScript form validation allows for more complex validation rules and works in all modern browsers. By adding event listeners to form elements, you can check the input value and provide feedback to the user if the input is invalid. While it requires more code than using HTML attributes, it provides more flexibility and customization options.
This tutorial covers some basic validations, but there are ways to enhance the validation process, such as:
Customizing the default error message provided by HTML5.
Displaying icons to indicate valid and invalid fields.
Triggering validation when an input field loses focus.
Top comments (0)