首页 > 解决方案 > 使用 PHP 进行表单验证不起作用

问题描述

我对 PHP 很陌生,我正在尝试使用三个输入字段验证一个简单的表单。出于某种原因,当我在字段为空时单击提交按钮时,我什么也没有返回。我已经为这个问题苦苦挣扎了好几个小时了。

我想要实现的是在字段为空/无效时在字段旁边获取错误文本。

这是我的 HTML 和 PHP 代码。

HTML:

<form method="post" action="">
    <table width="450px">
        <tr>
        <td valign="top">
            <label for="nimi">Nimi</label>
        </td>
        <td valign="top"> 

            <td><input type="text" name="nimi"><span class="error"><?php echo $nimiVirhe;?></span></td>
        </td>
        </tr>

        <tr>
        <td valign="top">
            <label for="sposti">Sähköposti</label>

        </td>
        <td valign="top">
            <td><input type="text" name="sposti"><span class="error"><?php echo $spostiVirhe;?></span></td>
        </td>
        </tr>

        <tr>
        <td valign="top">
            <label for="palaute">Palaute</label>
        </td>
        <td valign="top">
            <textarea  name="palaute" maxlength="1000" cols="30" rows="6"></textarea><span class="error"><?php echo $palauteVirhe;?> </span>
        </td>
        </tr>

        <tr>
        <td colspan="2" style="text-align:center">
        <input type="submit" value="Lähetä" name="submit">
        </td>
        </tr>


    </table>

</form>

PHP

<?php

$nimiVirhe = $spostiVirhe = $palauteVirhe = "";
$nimi = $sposti = $palaute = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["nimi"])) {
        $nimiVirhe = "Name is required";
    } else {
        $nimi = test_input($_POST["nimi"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$nimi)) {
            $nimiVirhe = "Only letters and white space allowed";
        }
    }

    if (empty($_POST["sposti"])) {
        $spostiVirhe = "Contact is required";
    } else {
        $sposti = test_input($_POST["sposti"]);
        if (!filter_var($sposti, FILTER_VALIDATE_EMAIL)) {
            $spostiVirhe = "Invalid email format";
        }
    }

    if (trim($_POST["palaute"]) == "") {
        $palauteVirhe = "City is required";
    } else {
        $palaute = test_input($_POST["palaute"]);
    }
}


function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

?>

我不知道下一步该尝试什么。

我在这里先向您的帮助表示感谢!

标签: phphtmlformsvalidation

解决方案


推荐阅读