David Cholariya
David Cholariya

Reputation: 3

How to find out whether at-least one field in a form is empty?

Hello guys I faced with problem. I have big form and there are no required fields. But before I submit it, I need to check is there an empty field. So I decided to use object for this task.

$scope.formData = {
  foo: "",
  bar: "",
  some: ""
};

I tried to use smth like this

function hasEmptyProperty (obj) {
  for(var key in obj) {
    if(obj.hasOwnProperty(key))
      if (obj[key].length > 0)
        return false;
    }
  return true;
}

but after execute, function may return false then true then false.

So my question is. How I can check if at least one property value in object is empty?

Upvotes: 0

Views: 876

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

For this problem you need to change the logic:

function hasEmptyProperty(obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key))
            if (obj[key].length === 0) // empty vs content
                return true;           // true vs false and short circuit
    }
    return false;                      // false vs true
}

But I suggeest to use Array#some()

The some() method tests whether some element in the array passes the test implemented by the provided function.

function hasEmptyProperty(obj) {
    return Object.keys(obj).some(function (key) {
        return !obj[key].length;
    });
}

var $scope = {};

$scope.formData = {
    foo: "",
    bar: "",
    some: ""
};

document.write('<pre>' + JSON.stringify(hasEmptyProperty($scope.formData), 0, 4) + '</pre>');

Upvotes: 1

Related Questions