如何验证输入是否为数字

时间:2019-01-10 15:00:14

标签: php

我有一个简单的系统,可以计算费率,如何验证是否输入了数值?我使用is_numeric但只能使用一个变量,替代品是什么?

显示此错误: 警告:is_nan()的期望值恰好为1,第10行的C:\ xampp \ htdocs \ imposto \ processar.php中给出的5

遵循html代码:

<html lang="pt-br">

<head>
    <title>Calc - Imposto</title>
</head>
<body>
    <h2>SISTEMA DE CÁLCULO DE IMPOSTOS</h2>
<h3>Subistua vírgula por ponto "."</h3>
<form method="POST" action="processar.php">
    <label>Valor Total: </label>
    <input type="text" name="valorTotal" style="width: 100px;"></br></br></br>

    % <input type="text" name="porcentagem1" style="width: 100px;"></br></br>

    % <input type="text" name="porcentagem2" style="width: 100px;"></br></br>

    % <input type="text" name="porcentagem3" style="width: 100px;"></br></br>

    % <input type="text" name="porcentagem4" style="width: 100px;"></br></br>

    <input type="submit" value="Enivar" >


     <input type="reset">
</form>

</body>
</html>

按照代码php:

<
?php

$valortotal = $_POST['valorTotal'];
$porcentagem1 = $_POST['porcentagem1'];
$porcentagem2 = $_POST['porcentagem2'];
$porcentagem3 = $_POST['porcentagem3'];
$porcentagem4 = $_POST['porcentagem4'];


if(is_numeric($valortotal, $porcentagem1, $porcentagem2, $porcentagem3, $porcentagem4)){
    echo "Por favor, digite apenas números";
}

?>

2 个答案:

答案 0 :(得分:2)

is_numeric仅检查1个变量。

您必须编写一个if语句,如下所示:

    if(is_numeric($valortotal) && is_numeric($porcentagem1) && is_numeric($porcentagem2) && is_numeric($porcentagem3) && is_numeric($porcentagem4))
    {
        echo "Por favor, digite apenas números";
    }

注意:如果所有变量均为数字,则仅回显“ Poravour,digite apenasnúmeros”。

答案 1 :(得分:0)

首先,您的<?php分两行。 第二个错误告诉您is_numeric期望使用您已为其指定5的参数。

为了检查所有5个变量,您可以对每个变量使用&&,以便对is_numeric()进行5次不同的调用,或者可以做一个数组遍历,并检查每个变量是否为数字< / p>

<?php
$valortotal = $_POST['valorTotal'];
$porcentagem1 = $_POST['porcentagem1'];
$porcentagem2 = $_POST['porcentagem2'];
$porcentagem3 = $_POST['porcentagem3'];
$porcentagem4 = $_POST['porcentagem4'];

$Verify_Int = array(
    $valortotal,
    $porcentagem1,
    $porcentagem2,
    $porcentagem3,
    $porcentagem4
);

foreach ($Verify_Int as $element) {
    if (is_numeric($element)) {
        echo var_export($element, true) . " is numeric", PHP_EOL;
    } else {
        echo var_export($element, true) . " is NOT numeric", PHP_EOL;
    }
}
?>
相关问题