Remove error messages
Introduction
Section titled βIntroductionβBefore we calculate and display the results of the userβs input, we need to remove any previous error messages that may have been displayed.
This is important because we donβt want to confuse the user with multiple error messages after they have fixed them.
Create a removeErrors()
function
Section titled βCreate a removeErrors() functionβ-
To remove the error messages, we will create a new function called
removeErrors()
.Just after your
displayErrors(errors)
function, add the following code:validateForm.js export function displayErrors(errors) {24 collapsed linesfor (let field in errors) {let inputElement = document.querySelector(`#${field}`);let labelElement = document.querySelector(`label[for=${field}]`);if (inputElement) {inputElement.classList.add("error-input");}if (labelElement) {labelElement.classList.add("error-label");}// Populate the error message div with an unordered list of error messageslet errorDiv = document.querySelector(`#${field}-error`);if (errorDiv) {errorDiv.classList.add("error-message");let ul = document.createElement("ul");errors[field].messages.forEach((message) => {let li = document.createElement("li");li.textContent = message;ul.appendChild(li);});errorDiv.innerHTML = ""; // Clear any existing contenterrorDiv.appendChild(ul);}}}function removeErrors() {let errorInputs = document.querySelectorAll(".error-input");errorInputs.forEach((input) => {input.classList.remove("error-input");});let errorLabels = document.querySelectorAll(".error-label");errorLabels.forEach((label) => {label.classList.remove("error-label");});let errorMessages = document.querySelectorAll(".error-message");errorMessages.forEach((div) => {div.classList.remove("error-message");div.innerHTML = "";});}export function validateForm({ userEmail, userLevel, userHours }) {55 collapsed linesconst maxHoursPerLevel = {basic: 5,advanced: 10,};let errors = {};// Helper function to add error messagesfunction addError(field, message) {if (!errors[field]) {errors[field] = { messages: [] };}errors[field].messages.push(message);}// Check if the user has provided an email addressif (userEmail === "") {addError("email", "Please enter your email address.");}// Check if the user has selected a levelif (userLevel === "") {addError("level", "Please select a level of study");}// Check if the user has specified at least one hour of studyif (isNaN(userHours) || userHours <Steps 1) {addError("hoursPerWeek", "Please enter at least one hour of tuition.");}// Check if the userLevel exists in the maxHoursPerLevel objectif (!maxHoursPerLevel.hasOwnProperty(userLevel)) {addError("level", "Invalid level of study selected.");}// Check if the number of hours requested is within the allowed rangeconst maxAllowedHours = maxHoursPerLevel[userLevel];if (userHours > maxAllowedHours) {addError("hoursPerWeek",`You can only study a maximum of ${maxAllowedHours} hours per week.`);}if (Object.keys(errors).length > 0) {displayErrors(errors);return false;}return {userEmail,userLevel,userHours,};} -
Navigate down to the
validateForm()
function and look carefully at the code inside. -
Save your changes and refresh the browser.
Enter some invalid data into the form and submit it, then check that the error messages are removed when you correct the information and submit the form again:
Summary
Section titled βSummaryβIn this step, we have:
- Created a new function called
removeErrors()
to remove any existing error messages from the form. - Called the
removeErrors()
function at the beginning of thevalidateForm()
function to ensure that any existing error messages are removed before the form is validated. - Tested the form to ensure that the error messages are removed when the user corrects the information and submits the form again.
Next steps
Section titled βNext stepsβIn the next step, we will calculate the results of the userβs input and print these values to the console in the browser.