
Prevent Form Submission if Username and Password Are Empty Using JavaScript
Last updated 2 weeks, 4 days ago | 59 views 75 5

Ensuring that required fields are filled before submitting a form is one of the most basic and essential aspects of client-side form validation. In this article, we’ll walk through how to stop a form from submitting if the username and password fields are left blank using vanilla JavaScript.
✅ Why Validate on the Client Side?
-
To give immediate feedback to the user
-
To prevent unnecessary server calls
-
To improve user experience
⚠️ Always validate on the server side too, as client-side validation can be bypassed.
Basic Form Structure
Let’s start with a simple login form:
<form id="loginForm">
<label>Username:</label>
<input type="text" id="username" /><br /><br />
<label>Password:</label>
<input type="password" id="password" /><br /><br />
<button type="submit">Login</button>
</form>
JavaScript: Prevent Form Submission
We’ll attach an event listener to the form’s submit
event. If either field is empty, we’ll:
-
Stop the form from submitting using
event.preventDefault()
-
Optionally, show an alert or message to the user
✅ Step-by-Step Breakdown
// Step 1: Wait until the DOM is fully loaded
document.addEventListener("DOMContentLoaded", function () {
const form = document.getElementById("loginForm");
const username = document.getElementById("username");
const password = document.getElementById("password");
// Step 2: Attach a submit event listener
form.addEventListener("submit", function (event) {
// Step 3: Check if either field is empty
if (username.value.trim() === "" || password.value.trim() === "") {
// Step 4: Stop the form from submitting
event.preventDefault();
// Step 5: Notify the user
alert("Both username and password are required.");
}
});
});
Complete Working Example (HTML + JS)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Login Validation</title>
</head>
<body>
<h2>Login</h2>
<form id="loginForm">
<label>Username:</label>
<input type="text" id="username" /><br /><br />
<label>Password:</label>
<input type="password" id="password" /><br /><br />
<button type="submit">Login</button>
</form>
<script>
document.addEventListener("DOMContentLoaded", function () {
const form = document.getElementById("loginForm");
const username = document.getElementById("username");
const password = document.getElementById("password");
form.addEventListener("submit", function (event) {
if (username.value.trim() === "" || password.value.trim() === "") {
event.preventDefault();
alert("Both username and password are required.");
}
});
});
</script>
</body>
</html>
Tips
-
Use
trim()
to avoid inputs with only spaces being considered valid. -
Consider displaying error messages inline instead of
alert()
for better UX. -
Use
required
attributes in HTML for basic HTML5 validation—but don’t rely on them alone.
⚠️ Common Pitfalls
Problem | Solution |
---|---|
Form still submits even if empty | Make sure you're calling event.preventDefault() inside the listener |
Fields filled with spaces | Use .trim() to remove spaces |
Listener doesn’t fire | Ensure JavaScript runs after the DOM is loaded or placed at the bottom of the page |
Doesn’t work in older browsers | This code is compatible with IE9+, but test if you target legacy browsers |
✅ Bonus: Inline Error Message Example
Instead of using alert()
, you can show inline messages:
<p id="errorMsg" style="color: red;"></p>
const errorMsg = document.getElementById("errorMsg");
if (username.value.trim() === "" || password.value.trim() === "") {
event.preventDefault();
errorMsg.textContent = "Both fields are required.";
}
Conclusion
Validating form inputs like username and password on the client side is a crucial first line of defense. By preventing form submission when required fields are empty, you provide a smoother, more intuitive user experience.
Would you like this turned into a React, Vue, or Bootstrap-enhanced version next? Click here
or
See Validation example to include PHP code for form submission. Click here