php - 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我也在考虑将验证代码放入一个单独的文件中,该文件将保存到包含文件夹中。
解决方案
数据将通过 $_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/也有很多好东西。
推荐阅读
- makefile - 有没有办法让一个makefile自动下载另一个makefile?
- karate - 如何在下一个请求中使用响应标头中的位置?
- python - 如何让 matplotlib.Figure() 接受 Drop 事件来绘制数据?
- php - 使“用户编写的脚本”由服务器处理
- powershell - 如何让powershell显示当前目录
- python - 如何解决此问题中的错误?
- r - 如何使用 r 从 phenoscanner 数据库中提取 gwas 数据
- algorithm - 要从字符串中删除的字母数,以便它可以被另一个字符串整除
- android - 从 Google Play 下载后,Android 应用程序在启动时崩溃
- python - 使用 CGI 模块在 Python http.server 中访问表单数据值