PHP表单验证,其中value不为null

时间:2013-04-03 07:34:59

标签: php validation isnumeric

尝试验证字段时,它似乎不起作用。我需要在!is_numeric不是$postcode时才执行null。我确实有客户端验证,但我想确保我也有服务器端验证。

代码:

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>';
}

3 个答案:

答案 0 :(得分:2)

假设$postcode来自$POST$GET,它始终是一个字符串。因此!is_null()将是假的,无论如何:

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

你可以恢复使用更自由的empty()。但是,当涉及到这些检查时,PHP完全不一致和奇怪。例如,empty()也会返回FALSE为0。烨。

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

更好的方法是做一些“duck-typing”。在您的情况下:当它可以转换为数值时,执行此操作并使用它。然后将它留给语言来确定它认为“number-ish”足以转换的内容。

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

所以:

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

最后,偏离主题:关注您的业务假设的警告:邮政编码并不总是数字。是的,在美国大部分都是。但是那里有更多的国家(说这是一个欧盟公民,他们过于频繁地认为每个人都是普通美国公民的网站)

答案 1 :(得分:2)

也许你想在strlen()函数上使用empty()函数,因为is_null()检查NULL值。如果$ postcode是==“”那么它不是NULL。

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

比你可以使用

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

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

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

如链接中所指定的,如果要使用is_null,最好使用$ postcode!== NULL。 快得多

答案 2 :(得分:0)

试试这个

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

希望这有帮助