I have an HTML form with a button which when clicked, it will check whether or not the fields are empty. Here is part of my code which does the validation(it works):
var errorMessage ="";
if (document.getElementById('username').value == "")
{
errorMessage += "Please enter a username \n";
document.getElementById('username').style.borderColor = "red";
}
if (document.getElementById('fname').value == "")
{
errorMessage += "Please enter a first name \n";
document.getElementById('fname').style.borderColor = "red";
}
if (document.getElementById('lname').value == "")
{
errorMessage += "Please enter a last name \n";
document.getElementById('lname').style.borderColor = "red";
}
if (errorMessage != "")
{
alert(errorMessage);
}
My problem is because I have more fields which require validation, I am wondering if there is a better way of doing this rather than having so many if statements (I'm trying to have as little code as possible). I was thinking of using a switch case statement but would that work? Any suggestions?