Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to validate a form in javascript

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?

like image 618
littledevils326 Avatar asked Nov 02 '22 12:11

littledevils326


1 Answers

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.

like image 59
Zaffy Avatar answered Nov 09 '22 05:11

Zaffy