PHP form validation where value is not null

775

When attempting to validate a field, it doesn't seem to work. I need to only perform!is_numeric when$postcode is notnull. 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>';
}
589

Answer

Solution:

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

158

Answer

Solution:

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 usingempty(), which is more liberal. However, PHP is utterly inconsistent and weird when it comes to these checks. For example,empty() will returnFALSE 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)

240

Answer

Solution:

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

People are also looking for solutions to the problem: Connect to PHP MySQL with Javascript from external server

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.