Clean this JS up

You could start by moving common code out to a separate function, such as for when an error occurs:

function fieldError(field, type, message) {
    document.getElementsByClassName(type)[0].innerHTML = "Error: " + message + " Please try again.";
    document.getElementsByClassName(type)[0].classList.remove("hide");
}

So that you can then use it from different related areas:

if(!validateEmail(email.value))
{
    fieldError(emailInput, "email-error", "Invalid username.");
    ...
}

Then you can look for other types of duplication and deal with them.

You may also want to browse through this code review of form validation where a large post was made detailing how improvements are made using a variety of different helpful beneficial techniques.

2 Likes