0

I must be having a massive brain fart today...

I am trying to make sure that either a ZipCode, or a City is entered into the form

$zip = @$_POST['ZipCode'];
$city = @$_POST['City'];

// validate, at least zipcode and radius if not City/radius
$errMsg = '';
$valid = true;
$valCity = (isset($city) && strlen($city) > 0);
$valZip = (isset($zip) && strlen($zip) > 0);

if(!(!$valCity && $valZip) || ($valCity && !$valZip)){
    $errMsg .= '<p>Please make sure at least a city/town, or zip code is entered.</p>';
    $valid = false;
}

ZipCode only works, City only does not work. What am I doing wrong?

3 Answers 3

4

Your code is little bit more complicated than it needs to be, and you're using isset where you really need to use empty.

$zip = $_POST['ZipCode'];
$city = $_POST['City'];

// validate, at least zipcode and radius if not City/radius
$errMsg = '';
$valid = true;

if(empty($zip) && empty($city)){
    $errMsg .= '<p>Please make sure at least a city/town, or zip code is entered.</p>';
    $valid = false;
}

If both $zip and $city are empty, then the message will be set and $valid will become false.

The difference is that empty() will check the value of a variable, where isset() will check the presence of the variable, so by setting $zip and $city, whether they were null or not, isset() would always return true for them.

-- UPDATE --

Just FYI, empty will also check string length, so there's no need to do both.

Sign up to request clarification or add additional context in comments.

Comments

1

Your if is a little more complicated than it needs to be...

if(!($valCity || $valZip)){
    $errMsg .= '<p>Please make sure at least a city/town, or zip code is entered.</p>';
    $valid = false;
}

This says that both valCity and valZip need to be true. If either is false, your message will display.

4 Comments

please see the question. I need either/or... not both as required
Fixed... your condition just needs to be an OR. If either is true, this will work.
I did clarify exactly in the question, read it again and you will see ZipCode only works, City only does not work. What am I doing wrong?
The core problem is the code above, not the if statement, this approach won't help at all.
0

Use this:

if(!isset($zip) || !isset($city)){
    $errMsg = '<p>Please make sure at least a city/town, or zip code is entered.</p>';
    $valid = false;
}

And this:

$errMsg .=

Can rather be:

 $errMsg =

And doesn't have to be defined like this:

$errMsg = '';

Before the if function. At the top somewhere of your code.

1 Comment

isset() is the wrong function to be using here, unless you're using it on the $_POST variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.