Form Validation When Submit Button is Disabled
In this pattern, the submit button is initially disabled and will only become enabled when all required fields are filled. Form validation occurs when the user tabs from one field to another using the Tab key. The email field also provides a suggestion that the correct format is not provided when it fails validation.
Working Example
Code
<form>
<div class="form-control">
<label for="email">Email:</label>
<input type="email" id="email" name="email" class="required">
<div class="error" id="email-error" aria-live="polite"></div>
</div>
<div class="form-control">
<label for="password">Password:</label>
<input type="password" id="password" name="password" class="required">
<div class="error" id="password-error" aria-live="polite"></div>
</div>
<div class="form-control">
<input type="submit" value="Submit" id="submit-button" disabled>
</div>
</form>
<style>
.form-control {
margin-bottom: 20px;
}
.error {
color: red;
display: none;
}
.required::before {
content: "* ";
color: red;
}
</style>
<script>
const emailField = document.getElementById("email");
const passwordField = document.getElementById("password");
const submitButton = document.getElementById("submit-button");
emailField.addEventListener("blur", validateEmail);
passwordField.addEventListener("blur", validatePassword);
function validateEmail() {
const emailValue = emailField.value.trim();
const emailError = document.getElementById("email-error");
if (emailValue === "") {
emailError.textContent = "Email is required.";
emailError.style.display = "block";
} else if (!isValidEmail(emailValue)) {
emailError.textContent = "Email must be in the format [email protected].";
emailError.style.display = "block";
} else {
emailError.textContent = "";
emailError.style.display = "none";
}
checkFormValidity();
}
function validatePassword() {
const passwordValue = passwordField.value.trim();
const passwordError = document.getElementById("password-error");
if (passwordValue === "") {
passwordError.textContent = "Password is required.";
passwordError.style.display = "block";
} else {
passwordError.textContent = "";
passwordError.style.display = "none";
}
checkFormValidity();
}