PixelPaul PixelPaul - 7 months ago 12
Javascript Question

Returning 'true' after validation function

I trying to verify that some fields have valid input before continuing. I want to only validate a few fields prior to form submission. The validation is working correctly and displaying errors where necessary. But when all fields are valid, it seems to not return to the calling function to continue?

function validateTableRow() {
$('input[name="addPid"]').valid();
$('input[name="addName"]').valid();
$('input[name="addAddress"]').valid();
$('input[name="addCity"]').valid();
$('select[name="addState"]').valid();
$('input[name="addZip"]').valid();
}

$('.button').click(function () {
if(validateTableRow()){
//Do something
}
});
}

Answer

Your function validateTableRow() has to return true in order to do the //Do something. But is not returning anything, to JS that's false, so whatever you put inside the if will not be done.

You can change the function to return true or false depending on what you want:

function validateTableRow() {
  return  $('input[name="addPid"]').valid() &&
    $('input[name="addName"]').valid() &&
    $('input[name="addAddress"]').valid() &&
    $('input[name="addCity"]').valid() &&
    $('select[name="addState"]').valid() &&
    $('input[name="addZip"]').valid();
}

$('.button').click(function () {
    if(validateTableRow()){
    //Do something
    }
});
}

[EDIT] To check them all before returning true or false, could be like this:

function validateTableRow() {

    $('input[name="addPid"]').valid();
    $('input[name="addName"]').valid();
    $('input[name="addAddress"]').valid();
    $('input[name="addCity"]').valid();
    $('select[name="addState"]').valid();
    $('input[name="addZip"]').valid();

    return  $('input[name="addPid"]').valid() &&
        $('input[name="addName"]').valid() &&
        $('input[name="addAddress"]').valid() &&
        $('input[name="addCity"]').valid() &&
        $('select[name="addState"]').valid() &&
        $('input[name="addZip"]').valid();
    }

    $('.button').click(function () {
        if(validateTableRow()){
        //Do something
        }
    });
    }