如何保护HTML表单不被空白提交 [英] How to protect HTML form from blank submission

查看:158
本文介绍了如何保护HTML表单不被空白提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在使用本教程: HTML FORM

Basically I'm using this tutorial: HTML FORM

一切正常,但我发现一个流程是,每个人都可以看到您的.phpURL,在本例中为"url:"contact_mail.php" 当有人键入url并按Enter时,是否有一种方法可以保护我的表单免于空白提交. 示例:www.mywebsite.com/contact_mail.php

Everything is working as it should but one flow I've found is that everyone can see the URL for your .php which in this case is "url: "contact_mail.php"" Is there a way to protect my form from blank submission when someone type the url and just press enter. Example: www.mywebsite.com/contact_mail.php

谢谢!

推荐答案

首先,您可以使用客户端必填字段上的required 属性:

First you can use the required attribute on mandatory fields for client-side:

<input type="text" name="mandatory_field" required>

但是如果用户修改了表单,您将需要验证服务器端.您可以在任何变量($_POST empty() >):

But you will need to verify server-side in case the user modified the form. You can use empty() on any variable ($_POST or $_GET):

if (empty($_POST['mandatory_field'])) {
    // print error message or redirect to form page
}

您可以使用 isset() 来验证是否提交了字段.您的验证可能是:

You can use isset() to verify if a field is submitted. Your validation could be:

if (!isset($_POST['mandatory_field']) || empty($_POST['mandatory_field'])) {
    // print error message or redirect to form page
}


其他情况:
如果所有字段都是必填字段,则可以使用 in_array() :


Other cases:
If all fields are mandatory you could check with in_array():

if (in_array(false, $_POST)) {
    // print error message or redirect to form page
}

如果要进行各种数据验证,这就是我用来处理表单的方法:

If doing various data validation here is what I use to do with forms:

$errors = [
    'empty field'           => empty($_POST['field']),
    'another error message' => $another_condition
];

if (in_array(true, $errors)) {
    $error_message = array_search(true, $errors);
    // print or redirect, and you can tell the user what is wrong
}

这篇关于如何保护HTML表单不被空白提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆