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?
You can use a table with data of fields and then just iterate over it.
var fields = [[document.getElementById("username"),"Please Enter Your Username"],
[document.getElementById("fname"), "Please Enter Your First Name"],
[document.getElementById("lname"), "Please Enter Your Last Name"]];
function Check()
{
var error = [];
for (var i in fields)
{
if (fields[i][0].value == "")
{
error.push(fields[i][1]);
fields[i][0].style.borderColor = "red";
}
}
if (error.length)
window.alert(error.join(",\n"));
return !error.length;
}
Note: probably you want o make sure that the value isnt empty so I would suggest you using something like: fields[i][0].value.replace(/\s/g, "") == ""
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With