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:
- Get input fields
- Store them in array with each one's value
- 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.
:inputinstead ofinputfor your selector, if you want to include<select>and<textarea>.for..inloop, you can use$.each. Instead ofvariable.valueyou can use$(variable).val(). Basically, use jQuery or get rid of it, because otherwise the readability of the code drops drastically if you're switching between straight JS and jQuery JS. (You'll thank yourself in the end, I promise.)for..inis a bad idea. It is used to enumerate an object's properties. A regularforloop should be used instead to iterate array values, or the$.eachthat jquery provides.$.eachthat jQuery provides and it works great. Thanks again.