In the first part of the series, we talked about the form in general – the HTML, the JS, form handling and spam prevention.
Now, we will look closer at form validation.
Read and check the input values
There are two input elements in our form – the email textbox and the dummy checkbox to prevent spam.
First, we need to read their values:
var emailInput = document.getElementById('email');
var email = emailInput.value.toString();
var checkbox = document.getElementById('contact_me');
Second, we check their values:
var valid = true;
if (checkbox.checked) {
valid = false;
} else if (email.length == 0) {
valid = false;
} else if (email.length > 100) {
valid = false;
} else if (!validateEmail(email)) {
valid = false;
}
Note:
- If the spam-preventing checkbox is checked, I automatically consider the input invalid and discard it. But you may want to process it, e.g. with a flag
canBeSpam
added. - Email address validation is a topic on its own, I was willing to use this imperfect regex in
validateEmail
function.
Display the error message
We display an error message when the input is not valid:
if (!valid) {
// set the color of the invalid input to red
emailInput.classList.add("red");
// create a new element
var errorTextElement = document.createElement('div');
// and give it a CSS ID, so that we can select it later
errorTextElement.setAttribute("id", "error");
// the element contains error message also in red
errorTextElement.classList.add("small");
errorTextElement.classList.add("red");
errorTextElement.textContent = 'The email is not valid.';
// append the new element to its parent
document.getElementById('email-container').appendChild(errorTextElement);
// re-enable the submit button
submitButton.removeAttribute('disabled');
submitButton.textContent = 'Let me know!';
return;
}
Note: The input can theoretically be invalid for two reasons: because the email is invalid or because the (invisible) checkbox is checked. Here, I am ignoring the possibility that the user could somehow check an invisible checkbox and assume that the error is always in the email.
Remove the old error message
When the user submits the form, there might already be an error message from the previous submission. Therefore we need to remove it before we start processing the new input:
// after the form is submitted
submitButton.textContent = 'Submitting...';
// remove previous error message
removeError();
// and start processing the new input
var emailInput = document.getElementById('email');
And what does removeError()
function do? It finds the element that contains the error message (the one we marked with error
CSS ID before) and removes it.
function removeError() {
// find the element containing an error message
var error = document.getElementById('error');
// if it exists, remove it
if (error != null) {
error.remove();
}
}
There is one more situation when we want to remove the error message, and that’s after it is displayed and the user starts typing again (presumably to fix the error). We do it every time onkeydown
event occurs:
<input id="email" class="u-full-width" type="text" name="email" placeholder="Your email" onkeydown="resetColor(this)">
The function is called resetColor
because we don’t only need to remove the error message, we also need to reset the color of the input back to normal, otherwise it would stay red.
function resetColor(element) {
element.classList.remove("red");
removeError();
}
And that is the most basic form validation.
Previous part
Source code
You can view the complete source code on Github.
Last modified on 2021-07-02