Search code examples
javascriptis-empty

Javascript Empty check


So, i have this code but something doesn't seem to work as expected.

function validateForm() {
    var x = document.forms["reg"]["username","password","first_name","last_name","age","mail"].value;
    if (x==null || x=="" || x==0) {
        alert("All fields must be filled out");
        return false;
    }
}

I get an alert if I leave any of the fields empty. Except for the last one. If I fill in every field except for mail, I can proceed. And if I only fill in mail, I can proceed as well.

How come it checks all the fields except the last one?

Or might there be an easier way to check if the fields are filled in? (I'm actually using PHP but somehow the if(empty($_POST['username']) thing doesn't work anymore, so I figured to just use JS, since it looks better with the alert message anyway.


Solution

  • You need to break your function up a little bit - put the field names into an array and loop through them one by one. And as stated in the comments, the null check isn't required.

    function validateForm()
    {
        var fields = ["username", "password", "first_name", "last_name", "age", "mail"];
        for(var i = 0; i < fields.length; i++)
        {
            var fieldName = fields[i];
            var x = document.forms["reg"][fieldName].value;
            if (x == "" || x == 0) {
                alert("All fields must be filled out");
                return false;
            }
        }
    }
    

    You should also do the same validation in your PHP code, as someone could easily disable JavaScript and so the data wouldn't get validated at all.