简体   繁体   English

如何在PHP中验证整数

[英]How to validate integer in php

** I'm creating a form application using php. **我正在使用php创建表单应用程序。 This code is not working properly. 此代码无法正常工作。 I want to show an error Student ID is required when it's empty. 我想显示一个错误的Student ID is required当它为空时Student ID is required的。 And the value must contain only 4 digits. 并且该值只能包含4位数字。 No string values and special characters can be entered. 不能输入字符串值和特殊字符。 All of the above should be validated. 以上所有内容均应经过验证。 how to solve this problem. 如何解决这个问题呢。 can any one help me please. 谁能帮我。 thanks... !!! 谢谢... !!! ** **

<!DOCTYPE html>
    <html>
        <head>
    <title> Enter Details </title>
        </head>
    <body>


<?php
    $id = "";
    $idErr = ""; 

if ($_SERVER["REQUEST_METHOD"] == "POST"){
        if (empty($id)){
            $idErr = "Student ID is required";
        }elseif(preg_match('/^\d+$/',$_GET['id'])){
            $idErr = "Only numbers allowed";
        }elseif(strlen($id) != 4) {
            $idErr = "Please enter  4 numbers";
        }
    }

    ?>

<form action = <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method = "post">
    Student ID: <input placeholder="Student ID" type = "text" name= "id" value = ""/> 
    <span class="error">* <?php echo $idErr;?></span></br></br>
        <input type = "submit" name = "submit" value = "Register"/> 
</form>

</body>
</html>

You define an empty variable and if the post submits you check if it's empty. 您定义一个空变量,如果帖子提交,则检查它是否为空。 This will always be true because this variable has an empty string as value. 这将始终为真,因为此变量具有一个空字符串作为值。 You should try to use $_POST . 您应该尝试使用$_POST You should also change $_GET['id'] into $_POST['id'] : 您还应该将$_GET['id']更改为$_POST['id']

<?php

$idErr = ""; 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = $_POST['id'];

    if (empty($id)){
         $idErr = "Student ID is required";
    } elseif(preg_match('/^\d+$/',$_POST['id'])) {
         $idErr = "Only numbers allowed";
    } elseif(strlen($id) != 4) {
         $idErr = "Please enter  4 numbers";
    }
}

?>

You should be able to get a different result if you try this. 如果您尝试此操作,则应该可以获得不同的结果。

    <?php
        $id = "";
        $idErr = ""; 
    if ($_SERVER["REQUEST_METHOD"] == "POST"){
            $idVal = $_POST['id'];
            if (empty($idVal)){
                $idErr = "Student ID is required";
            }elseif(!is_numeric($idVal)){
                $idErr = "Only numbers allowed";
            }elseif(strlen($idVal) != 4) {
                $idErr = "Please enter  4 numbers";
            }
        }
    ?>


//it check like below
   empty->number->exact 4 digit-> success.....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM