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>';
}
One Man Crew
  • 9,420
  • 2
  • 42
  • 51
DLO
  • 309
  • 2
  • 7
  • 17
  • what error you get it from the server? – Ranjith Apr 03 '13 at 07: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? – Seer Apr 03 '13 at 07:47

3 Answers3

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)

berkes
  • 26,996
  • 27
  • 115
  • 206
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

Giovanni Lovece
  • 230
  • 1
  • 8
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

Roger
  • 1,693
  • 1
  • 18
  • 34