首页 > 解决方案 > PHP 中的 HTML 表单验证。

问题描述

我对 php 完全陌生,经过研究,我仍然找不到合适的答案。当我尝试使用 php 验证我的表单并使用 CSS 自定义错误消息时。

我的 HTML 代码是:

<div class="container">
<form action="/action_page.php">
    <div class="flex-row">
        <input type="text" id="name" name="name" placeholder="Name">
        <input type="email" id="email" name="email" placeholder="Email Address">
        <input type="number" id="age" name="age" placeholder="Age">
    </div>
    <div class="flex-row">
        <input type="text" id="subject" name="subject" placeholder="Subject">
        <select type="dropdown" name="contact" placeholder="Age">
            <option placeholder="australia">Australia</option>
            <option value="canada">Canada</option>
            <option value="usa">USA</option>
        </select>
    </div>
    <div class="flex-row">
        <textarea id="message" name="message" placeholder="Talk To Us" style="height:200px"></textarea>
    </div>
    <input type="submit" value="Submit">
</form>

我的 CSS 在下面的 pastebin 上:

巴斯宾

我希望验证的表格

PS我也在考虑将验证代码放入一个单独的文件中,该文件将保存到包含文件夹中。

标签: phphtmlcss

解决方案


数据将通过 $_GET 全局变量作为数组在 php-script 中可用。每个输入都是该数组中的一个项目,例如 $_GET["name"]。脚本action_page.php可能看起来像这样(这只是一个开始......):

<?php
//Test the input, for example like this:
if(empty($_GET["name"])) $error="You need to provide a name";
if(strpos($_GET["email"],"@")==0) $error="The e-mail is not valid"; //Of course you could test for a lot more, for example using regular expressions

//Now you can build your response to the user
if($error) {
   echo ("<h1>Error</h1>".$error);
}
include("form.html"); //If you want to show the same form again. 

您还可以在表单中包含更多集成的错误 - 但是您需要将 PHP 集成到 HTML 中。

您可以在http://www.php.net找到很好的文档,并且http://w3schools.com/也有很多好东西。


推荐阅读