JQuery make sure all form fields are filled

I have a simple form for which I am doing client-side validation. To check, none of the fields should be empty. Here is how I understand it:

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

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

+8
javascript jquery validation forms
source share
4 answers

You cannot return false from an anonymous function. Also, if that worked, you will return false if your first field was empty, true if not, and completely ignore the rest of the 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 that you decorate all form fields with this formfield class. You may be interested in filtering using another selector, for example. $('form.validated-form input[type="text"]')

EDIT . Ah, I got hit, but my explanation is still relevant and hopefully helpful.

+23
source share

You were returning from an internal 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 } 
+4
source share
 function validateForm() { var invalid= 0; $('.form-field').each(function () { if ($(this).val() == '') { invalid++; } }); if(invalid>0) return false; else return true; } 
+1
source share

Here is a similar approach:

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

!! just converts the input value to bool

0
source share

All Articles