views:

263

answers:

3

Hello,

I am trying to write a simple input field validation plugin at the moment (more of a learning exercise really) and thought this would not be too hard, seeing as all I should have to do is:

  1. Get input fields
  2. Store them in array with each one's value
  3. On submit of form check if array contains any empty strings

But I seem to fail at writing something that checks for an empty string (read: input with no text inside) inside my array.

Here is the code I have so far:

var form = $(this), // passed in form element
    inputs = form.find('input'), // all of this forms input fields
    isValid = false; // initially set the form to not be valid


function validate() {
    var fields = inputs.serializeArray(); // make an array out of input fields

    // start -- this does not work
    for (var n in fields) {
        if (fields[n].value == "") {
            isValid = false;
            console.log('failed');
        } else {
            isValid = true;
            console.log('passed');
        };
    }
    // end -- this does not work

}; // close validate()

// TRIGGERS
inputs.live('keyup blur', function(event) {
    validate();
});

Any help with how I can check if one of the fields is blank and if so return a isValid = false would be much appreciated.

I also played around with the $.inArray("", fields) but this would never return 0 or 1 even when the console.log showed that the fields had no value.

Thanks for reading.

+4  A: 

If the first field is empty, and the second isn't, you'll overwrite the isValid variable that way. You can break; the for loop once you get the first empty variable.

Alec
Great answer. Makes perfect sense.
karim79
+1 - I completely overlooked this, good catch.
Nick Craver
Made it work just like I wanted. Thanks. Ultimately however I feel like the `$.each` approach is probably the better one seeing as this is a jQuery "plugin". Thanks though, definitely learned a lot.
Jannis
+3  A: 

If you are looking for a more-jQuery style syntax, you could replace your for loop using:

var isValid = true;  // default to valid

$.each(fields, function(i, field){
    if(field.value == '') {
        console.log('failed');   
        isValid = false; 
    } else {
        console.log('passed');
    }
});
uhleeka
thanks, this works great!
Jannis
A: 

You could replace the whole validate function with a bit of a simpler check:

function validate() {
    var blankInputs = inputs.filter(function() {
        return this.value === ''; 
    });

    isValid = blankInputs.length === 0; // If there are none, the form is valid

} // close validate()

Please note the use of the strict equality operator, ===. It is good practice to pretty much always use this instead of ==, but this is especially the case for values that act falsy (evaluate to false when you say if (value)). == can give you some very unexpected behavior in these cases.

Kent