2015-11-12 153 views
1

我有这个inupt领域检查用户只输入数字,PHP

<p style="font-size: 18px;">Total Bids: <input type="text" class="total_bids" name="total_bids" placeholder="No. of Bids"></p> 

通过获取其值:

var totalbids = document.getElementsByName('total_bids')[0].value; 

,并通过

$total_bids = PSF::requestGetPOST('totalbids'); 

一切都让PHP中的价值工作正常,但它应该只取数值,所以我试图检查用户是否只输入一个数字,如何定义字母范围s但愿我可以设置检查类似

if($total_bids== 'alphabet range') 
     { 
      return json_encode(array('error' => 'Please enter a valid Number.')); 
     } 
+1

'如果(is_numeric($ numberOrLetters)){...}'??? [php.net文档](http://php.net/manual/en/function.is-numeric.php) –

+0

这里是你回答:http://stackoverflow.com/questions/13779209/checking-that-a -value-contains-only-digits-regex-or-no – swidmann

回答

1

首先,您可以通过将其类型定义为type="number"来禁止该人输入除<input../>之外的任何数字。

显然,人们可以绕过它,所以你仍然需要在后端检查它,你需要使用像is_numeric()这样的函数。

2

您可以使用正则表达式和\d表达。 \d只匹配数字。

1

您可以通过is_numeric

if(!is_numeric($total_bids)) 
{ 
    return json_encode(array('error' => 'Please enter a valid Number.')); 
} 

还要检查,如果你想要做任何特殊的检查,您可以通过preg_match使用正则表达式,例如:

if(!preg_match('~^[\d\.]$~', $total_bids)) 
{ 
    return json_encode(array('error' => 'Please enter a valid Number.')); 
} 

正则表达式更加灵活,您可以添加您自己的规则检查通过regexpm但is_numeric检查更快然后正则表达式检查

1

根据您的输入,如果你只需要数字然后尝试ctype_digit

$strings = array('1820.20', '10002', 'wsl!12');//input with quotes is preferable. 
foreach ($strings as $testcase) { 
    if (ctype_digit($testcase)) { 
     echo "The string $testcase consists of all digits.\n"; 
    } else { 
     echo "The string $testcase does not consist of all digits.\n"; 
    } 
} 

在这里看到:http://php.net/ctype_digit

+0

这是一个不好的例子,因为ctype_digit(43)将返回false,它只会用于字符串 –

+0

@AntonOhorodnyk它应该被字符串引用。是检查数字的最佳选择。对于您的信息,op的输入是文本类型。 –

+0

更好地使用is_numeric来解决这个问题 –

1
if(preg_match ("/[^0-9]/", $total_bids)){ 
    return json_encode(array('error' => 'Please enter a valid Number.')); 
}