仅验证正整数

时间:2017-08-03 01:57:45

标签: php

问题

我需要验证一些输入。它应该只接受正整数。到目前为止,我的代码工作不正常。

我的代码

if ( !is_numeric($data['dollar']) {
  return FALSE; 
}

实施例

0 // TRUE
1 // TRUE
-1 // FALSE
0.9 // FALSE

4 个答案:

答案 0 :(得分:4)

if ( !ctype_digit($data['dollar']) ) { return FALSE; }

http://php.net/ctype_digit

答案 1 :(得分:0)

您可以使用validation functions

$type    = FILTER_VALIDATE_INT;
$options = [ 'min_range' => 1, 'max_range' => PHP_INT_MAX ];
if (false === filter_var($data['dollar'], $type, [ 'options' => $options ])) {
    return FALSE;
}

See it online at 3v4l.org

答案 2 :(得分:-1)

您可以使用下面的正则表达式来解决您的问题

return preg_match("/^[0-9]*$/",$data['dollar']);

答案 3 :(得分:-1)

您可以使用is_int()代替is_numeric()

相关问题