Question

I am trying to create my own simple form validation while looping through all the form elements with the class '.required' using each().

The problem is, it keeps breaking out of the loop and always jumps to 'return true;' even if all the fields are empty.

This is the html:

<input type="text" id="personal-name" name="personal-name" class="required-field" placeholder="First Name">

And this is the jQuery code:

function validForm() {

    var privacyApprove = $('#privacy-approved');
    var errorWindow = $('.errors');

    // Fade out the error after 3 seconds
    var errorFadeOut = setInterval(function () {
        errorWindow.fadeOut();
        clearInterval(errorFadeOut);
    }, 3000);

    if (!privacyApprove.is(':checked')) {
        errorWindow.fadeIn().text("יש להסכים לתנאי התקנון");
        return false;
    }

    $('input.required-field, textarea.required-field').each(function() {
            if ($(this).val() == 0) {
                errorWindow.fadeIn().text("אנא השלם את כל הפרטים הנדרשים המודגשים באדום");
                $(this).addClass('input-error');
            } else {
                $(this).removeClass('input-error');
            }
    });

    return true;
}

What am I doing wrong??

Thanks! :)

Was it helpful?

Solution

It seems you want to do

if ($(this).val() == '')

instead of

if ($(this).val() == 0)

A valid alternative would be

if ($(this).val().length == 0)

Also, you should avoid returning true always. Change your return value to this

return $('.input-error').length == 0

OTHER TIPS

If the code gets the the each block it will always return true. You do not have any logic that will return false.

Possible add something like this after the each

if ($('input-error'))
  return false
else
  return true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top