【发布时间】:2013-10-14 16:05:12
【问题描述】:
有更好的方法吗?
if( $_POST['id'] != (integer)$_POST['id'] )
echo 'not a integer';
我试过了
if( !is_int($_POST['id']) )
但is_int() 出于某种原因不起作用。
我的表单是这样的
<form method="post">
<input type="text" name="id">
</form>
我研究过is_int(),好像如果
is_int('23'); // would return false (not what I want)
is_int(23); // would return true
我也试过is_numeric()
is_numeric('23'); // return true
is_numeric(23); // return true
is_numeric('23.3'); // also returns true (not what I want)
看来唯一的办法是: [这是不好的办法,不要这样做,见下面的注释]
if( '23' == (integer)'23' ) // return true
if( 23 == (integer)23 ) // return true
if( 23.3 == (integer)23.3 ) // return false
if( '23.3' == (integer)'23.3') // return false
但是有没有实现上述功能的功能?
澄清一下,我想要以下结果
23 // return true
'23' // return true
22.3 // return false
'23.3' // return false
注意:我刚刚发现我之前提出的解决方案将对所有字符串返回 true。 (感谢 redreggae)
$var = 'hello';
if( $var != (integer)$var )
echo 'not a integer';
// will return true! So this doesn't work either.
这不是Checking if a variable is an integer in PHP 的重复,因为我对整数的要求/定义与那里不同。
【问题讨论】:
-
试试 RegEXP。
preg_match('/^[\d]*$/',$variable)!==FALSE -
为什么需要“验证”?你不能只过滤值吗?所以: $input = (int)$_POST['id'] 。这将为您提供 100% 安全的整数(如果出现问题,则为 0),并且更容易处理......
-
@Qualcuno 我正在考虑这个问题,但我想通知用户他们没有输入正确的数字并且不要为他们更改。
-
var_dump($_POST["id"]) 怎么样,这会告诉你数据类型;
-
为什么?假设他/她键入“aaa”,它将变为 0,您将拒绝它,就像您拒绝输入 0 一样。(因为它是一个 id,所以我想它会 > 0)。您只会告诉您的用户“输入错误”,无需进一步详细说明!
标签: php html validation