sf89
sf89

Reputation: 5248

jQuery make sure all form fields are filled

I have a simple form I'm making client side validation for. To validate, none of the fields should be left blank. This is how I go at it:

function validateForm() {
  $('.form-field').each(function() {
    if ( $(this).val() === '' ) {
      return false
    }
    else {
      return true;
    }
  });
}

For some reason, my function always returns false, even though all fields are filled.

Upvotes: 16

Views: 57218

Answers (4)

insane-dev
insane-dev

Reputation: 59

Here is a similar approach:

function validateForm() {
  var valid = true;
  $('.form-field').each(function() {
    valid &= !!$(this).val();
  });
  return valid;
}

!! just converts input value to bool

Upvotes: -1

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

function validateForm() {
    var invalid= 0;
    $('.form-field').each(function () {
        if ($(this).val() == '') {
            invalid++;
        }
    });

   if(invalid>0)
       return false;
   else
       return true;
}

Upvotes: 1

Guttsy
Guttsy

Reputation: 2119

You cannot return false from within the anonymous function. In addition, if it did work, you would return false if your first field was empty, true if not, and completely ignore the rest of your fields. There may be a more elegant solution but you can do something like this:

function validateForm() {
  var isValid = true;
  $('.form-field').each(function() {
    if ( $(this).val() === '' )
        isValid = false;
  });
  return isValid;
}

Another recommendation: this requires you to decorate all of your form fields with that formfield class. You may be interested in filtering using a different selector, e.g. $('form.validated-form input[type="text"]')

EDIT Ah, I got beat to the punch, but my explanation is still valid and hopefully helpful.

Upvotes: 38

Arun P Johny
Arun P Johny

Reputation: 388446

You were returning from the inner function not from the validate method

Try

function validateForm() {
    var valid = true;
    $('.form-field').each(function () {
        if ($(this).val() === '') {
            valid = false;
            return false;
        }
    });
    return valid
}

Upvotes: 6

Related Questions