我有这个inupt字段
<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;
并通过以下方式获取 PHP 中的值
$total_bids = PSF::requestGetPOST('totalbids');
一切正常,但它应该只取数字值,所以我正在尝试检查用户是否只输入一个数字,我如何定义字母范围以便我可以设置类似
if( $total_bids== 'alphabet range')
{
return json_encode(array('error' => 'Please enter a valid Number.'));
}
您可以使用正则表达式和'd
表达式。 'd
仅匹配数字。
首先,您可以通过将其类型定义为 type="number"
来禁止该人在<input../>
中输入除数字以外的任何内容。
显然,人们可以绕过它,所以你仍然需要在后端检查它,你需要使用像 is_numeric()
这样的函数。
你可以
按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.'));
}
正则表达式更灵活,您可以添加自己的规则来通过正则表达式进行检查,但is_numeric检查速度比正则表达式检查更快
if(preg_match ("/[^0-9]/", $total_bids)){
return json_encode(array('error' => 'Please enter a valid Number.'));
}
根据您的
输入,如果您只需要数字,请尝试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