1

When attempting to validate a field, it doesn't seem to work. I need to only perform !is_numeric when $postcode is not null. I do have client side validation, but I want to ensure that I have server side validation too.

code:

else if(!is_null($postcode) && !is_numeric($postcode))  
{
    $msg_to_user = '<br /><br /><h4><font color="FF0000">Postcode must be a numeric value.</font></h4>';
}
2
  • what error you get it from the server? Commented Apr 3, 2013 at 7:46
  • The code you've posted is fine apart from there isn't a semicolon at the end of the 2nd line. Like @Ranjith said, what error are you getting? Commented Apr 3, 2013 at 7:47

3 Answers 3

2

maybe you want to use empty() function on strlen() function because is_null() checks NULL value. If $postcode is == "" it's not NULL.

http://php.net/manual/en/function.is-null.php

than you can use

else if(!empty($postcode) && !is_numeric($postcode))  {

or

else if(strlen($postcode) > 0 && !is_numeric($postcode))  {

or

else if($postcode != "" && !is_numeric($postcode))  {

As specified in the link, if you want to use is_null, is better to use $postcode !== NULL. Much faster

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

Comments

2

Assuming $postcode comes from either a $POST or $GET, it always is a string. !is_null() will, therefore be FALSE, regardless:

php> var_dump(is_null(""))
#=> bool(false)

You could revert to using empty(), which is more liberal. However, PHP is utterly inconsistent and weird when it comes to these checks. For example, empty() will return FALSE for 0 too. Yup.

php> $postcode = "";
php> var_dump(empty($postcode))
#=> bool(true)
php> $postcode = 0;
php>var_dump(empty($postcode))
#=> bool(true)

A much better approach, is to do some sort of "duck-typing". In your case: when it can be converted to a numeric value, do that and use it. Then leave it to the language to determine what it considers "number-ish" enough to convert.

php> var_dump((int) "")
int(0)
php> var_dump((int) "13")
int(13)

So:

else if(($postcode = (int) $postcode) && ($postcode > 0)) {
}

And last, off-topic: a heed of warning about your business assumptions: postcodes are not always numeric. Yes, in the US most are. But there are more countries out there (saying this as a EU-citizen who comes way too often about sites that assume everyone is an average-US-citizen)

Comments

0

Try this

else if(!empty($postcode) && !is_numeric($postcode))  {
  $msg_to_user = '<br /><br /><h4><font color="FF0000">Postcode must be a numeric value.</font></h4>';
}

Hope this helps

Comments

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.