如何检查必填字段是否已填写?

如何解决如何检查必填字段是否已填写?

仅使用核心 PHP 而没有其他任何东西,例如 JavaScript 或客户端编程,我需要 PHP 检查表单的必填字段是否已填写,如果未填写则显示错误消息。我需要检查使用过程式编程,因为我还没有进入 OOP 并且不理解它。

HTML 表单

<html>
<head>
<title>
Searchengine Result Page
</title>
</head>
<body>

<form method = 'POST' action = "">
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<label for='url'>url</label>
<input type='url' name='url' id='url' required>
<br>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' required>
<br>
<label for='description'>description</label>
<input type='text' name='description' id='description' required>
<br>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' required>
<br>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' required>
<br>
<button type='submit'>Search!</button>
</form>
</body>
</html>

PHP 表单验证器

<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','keyword');

$required_labels_count = count($required_labels);

for($i=0; $i!=$required_labels_count; $i++)
{
    if(!ISSET(in_array(($_POST['$required_labels[$i]']),$required_labels))) //Incomplete line as I     don't know how to complete the code here.
    {
        echo 'You must fill-in the field' .'Missed field\'s label goes here'; //How to echo the missed field's label here ?
    }
}

?>

我知道我需要检查关联的数组值,因为这样会更容易且代码更少,但我不知道该怎么做。 注意我的错误回显。这是不完整的,因为我不知道如何编写代码的和平。 您将如何使用程序风格检查尽可能短的代码? 还有什么我需要知道的吗?

注意:我不想手动输入每个 $_POST[] 来检查是否填写了必需的。我需要 PHP 遍历 $required_labels[] 数组并检查。或者,如果您知道任何无需循环的更短的检查方法,那么我想知道。

解决方法

首先我们将有一个空的 $errors 数组,然后我们将应用验证,如果其中任何一个失败,我们将填充 $errors

最后使用辅助函数 errorsPrinter,我们将在标签下打印错误。

对于您的 PHP 验证部分,请使用以下代码。请注意,我还添加了用于验证 stringint 类型的部分。

<?php

$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','keyword');

$inputs = $_POST;
$errors = [];

foreach($required_labels as $label) {    
    if(!isset($inputs[$label]) || empty($inputs[$label])) {
        $errors[$label] = array_merge(
            ["You must fill-in the field."],$errors[$label] ?? []
        );
    }
}

foreach($strings_labels as $label) {    
    if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_string($inputs[$label])) {
        $errors[$label] = array_merge(
            ["This input should be string"],$errors[$label] ?? []
        );
    }
}


foreach($ints_labels as $label) {    
    if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_int($inputs[$label])) {
        $errors[$label] = array_merge(
            ["This input should be int"],$errors[$label] ?? []
        );
    }
}


function errorsPrinter($errors,$key)
{
    $output = '<ul>';

    if(!isset($errors[$key])) {
        return;
    }
    foreach($errors[$key] as $error) {
        $output = $output. '<li>' . $error . '</li>';
    }

    print($output . '</ul>');
}
?>

在表单中,您可以执行以下操作:

<form method='POST' action="">
    <?php errorsPrinter($errors,'submission_id') ?>
    <label for='submission_id'>submission_id</label>
    <input type='text' name='submission_id' id='submission_id'>
    <br>
    <?php errorsPrinter($errors,'website_age') ?>
    <label for='website_age'>website_age</label>
    <input type='text' name='website_age' id='website_age'>
    <br>
    <?php errorsPrinter($errors,'url') ?>
    <label for='url'>url</label>
    <input type='url' name='url' id='url' >
    <br>
    <?php errorsPrinter($errors,'anchor') ?>
    <label for='anchor'>anchor</label>
    <input type='text' name='anchor' id='anchor' >
    <br>
    <?php errorsPrinter($errors,'description') ?>
    <label for='description'>description</label>
    <input type='text' name='description' id='description' >
    <br>
    <?php errorsPrinter($errors,'keyphrase') ?>
    <label for='keyphrase'>keyphrase</label>
    <input type='text' name='keyphrase' id='keyphrase' >
    <br>
    <?php errorsPrinter($errors,'keyword') ?>
    <label for='keyword'>keyword</label>
    <input type='text' name='keyword' id='keyword' >
    <br>
    <button type='submit'>Search!</button>
</form>

请注意,errorsPrinter 只是一个助手,您可以将其删除并根据需要使用 $errors 数组。错误的示例输出是这样的:

[
    "url" => ["You must fill-in the field."],"anchor" => ["You must fill-in the field."],"description" => ["You must fill-in the field."],"keyphrase" => ["You must fill-in the field."],"keyword" => ["You must fill-in the field."],"website_age" => ["This input should be int"]
]
,
$errors = [];    
foreach($required_labels as $field) {
  if (!isset($_POST[$field]) || $_POST[$field] == '') {
    $errors[$field] = "{$field} cannot be empty";
    // echo "${field} cannot be empty";
  }
}

然后输出这些错误:

<?php 
if (count($errors)) {
?>
  <div id='error_messages'>
    <p>Sorry,the following errors occurred:</p>
    <ul>
    <?php
    foreach ($errors as $error) {
      echo "<li>$error</li>";
    }
    ?>
    </ul>
  </div>
<?php
}

你也可以直接在输入旁边输出错误:

<input type="text" id="first_name" name="first_name" placeholder="First Name" />
<?php if (isset($errors['first_name'])) echo "<div class='error_message'>{$errors['first_name']}</div>";?>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-