Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning true or false from javascript function

I'm doing a regex check on a string within a function:

function ValidateZipCodeString(listOfZipCodes) {
    var regex = /^([, ]*\d{5})+[, ]*$/,
    matches = regex.exec(listOfZipCodes);

    if (regex.exec(listOfZipCodes) === null) {
        console.log('validation failed');
        return false;
    } else {
        console.log('validation passed');
        return true;
    }
}

The regex is correctly detecting a valid/invalid list of zip codes.

I'm calling the function with this:

console.log('zip code: ' + listOfZipCodes);
if (ValidateZipCodeString(listOfZipCodes)) {
    $tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
    console.log('validate function returned true');
}

The problem is that the above if/else goes to the else clause, when the console output within the validation function shows "validation failed". So I must not be calling that function right.

What's the correct way to do what I'm trying to do?

like image 204
marky Avatar asked Dec 08 '22 18:12

marky


1 Answers

Your function could be greatly simplified to:

function ValidateZipCodeString(listOfZipCodes) {
    var regex = /^([, ]*\d{5})+[, ]*$/;

    if (regex.test(listOfZipCodes)) {
        console.log('validation passed');
        return true;
    } else {
        console.log('validation failed');
        return false;
    }
}

...or:

function ValidateZipCodeString(listOfZipCodes) {
    var regex = /^([, ]*\d{5})+[, ]*$/;
    return regex.test(listOfZipCodes);
}

...or even just:

function ValidateZipCodeString(listOfZipCodes) {
    return /^([, ]*\d{5})+[, ]*$/.test(listOfZipCodes);
}

...but the real issue (as Teemu points out) is not in your function, but in the use of it. Your function answers the question, "Is this a valid zip code string?", but your use of it is saying, "Say this is invalid if my function says it is."

like image 114
Grinn Avatar answered Dec 14 '22 22:12

Grinn