在 php 验证中生成错误消息

Producing error messages in php validation

提问人:Blood Seeker 提问时间:3/5/2022 最后编辑:RiggsFollyBlood Seeker 更新时间:3/11/2022 访问量:124

问:

我正在尝试使用 php 验证表单,我拥有的代码不会阻止在输入无效时提交表单,但是,我希望它们显示的错误消息不会显示在表单上,即使我在表单中回显了错误消息,表单也返回了空。你能帮我在提交表格失败时显示错误信息吗?我添加了表单代码和 PHP 代码。两者都是单独的文件,表单中的操作会导致PHP验证代码,如下所示(action = “report_form_php.php)。

<form  method="post" onsubmit=" return formSubmit()" action="report_form_php.php">
      <div class="error1" id= "errorMsg">* Required Fields</div>
      <div class="error" id= "errorMsg1">*<?php echo $staffErr; ?></div>
      <div>
      <label for="staff_name"><b>Staff Name:</b></label> 
      <input  class="field" id="staff_name" name="staffname" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name"   > 
      </div><br>

      <div class="error" id= "errorMsg2">*<?php echo $emailErr; ?></div>
      <div>
      <label for="email"><b>Email:</b></label> 
      <input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="[email protected]" >  
      </div><br>
      <div class="error" id= "errorMsg3">*<?php echo $subjectErr; ?></div>
      <div>
      <label for="subject"><b>Subject:</b></label> 
      <input  class="field" name="subject" id="subject1" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title"  > 
      </div><br>

      <div class="error" id= "errorMsg4">*<?php echo $problemErr; ?></div>
      <div>
        <select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
            <option value="">Problem Type</option>
            <option value="Hardware">Hardware</option>
            <option value="Software">Software</option>
            <option value="Software&Hardware">Software & Hardware</option>
            <option value="Other">Other</option>
          </select>
      </div><br>
      <div class="error" id= "errorMsg5">*<?php echo $descriptionErr; ?></div>
      <div>
      <textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here"   rows="15" cols="90"></textarea>
      </div>          
      
      <div>
        <button class="field3" type="submit" class="btn">Submit</button>
        <input type="checkbox" id="notify" name="notify" value="">
        <label for="notify">Inform me by email when issue is resolved.</label> 
    </div>
</form>

<?php
// define variables and set to empty values
$staffErr = $emailErr = $subjectErr = $problemErr = $descriptionErr= "";
$staffname = $email = $subject = $problem_type = $description = "";

// staff name validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["staffname"])) {
        $staffErr = "Staff Name is required";
    } else {
        $staff_name = test_input($_POST["staffname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' ]*$/",$staffname)) {
            $staffErr = "Only letters and white space allowed";
        }
    }

    // email validation:
    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Please enter a valid email.";
        }
    }

    // subject validation:

    if (empty($_POST["subject"])) {
        $subjectErr = "Subject is required";
    } else {
        $subject = test_input($_POST["subject"]);
        // check if subject only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' ]*$/",$subject)) {
        $subjectErr = "Only letters and white space allowed";
        }
    }

    // problem type validation:

    if (empty($_POST["problem_type"])) {
        $problemErr = "Problem type is required";
    } else {
        $problem_type = test_input($_POST["problem_type"]);
    }

    // description validation:

    if (empty($_POST["description"])) {
        $descriptionErr = "A Description is required";
    } else {
        $description = test_input($_POST["description"]);
    }
}


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

if ($staffErr == "" && $emailErr == "" &&$subjectErr == "" &&$problemErr == "" &&$descriptionErr == "") {
    header("Location: insert_logs.php");
    exit(); 
} else {
    header("Location: log-it-reportsbeta.php");
    exit(); 
}
?>

php html 验证 服务器端

评论

0赞 RiggsFolly 3/5/2022
然而,大量的空白无助于理解代码!!好的代码缩进将帮助我们阅读代码,更重要的是,它将帮助您调试代码 为了您自己的利益,快速浏览一下编码标准。您可能会被要求在几周/几个月内修改此代码,您最终会感谢我。
0赞 N. Kern 3/5/2022
你设置了吗?因为如果您在 PHP 中没有看到任何错误/通知,您的 Web 服务器可能使用的默认值为 0(不显示任何内容)。ini_set('display_errors', 1);
0赞 Don't Panic 3/5/2022
在哪里,它有什么作用?浏览器之后如何返回表单?formSubmit()report_form_php.php
0赞 Blood Seeker 3/5/2022
@Don'tPanic formSubmit() 是一个用于客户端验证的 javascript 函数,它在不同的 js 文件中,工作正常.问题是php,如果提交成功,浏览器会转到页面<insert_logs.php>,我有一个返回链接,如果提交不成功,浏览器应该重新加载同一页面并显示错误消息,现在的问题是缺少错误消息
0赞 Blood Seeker 3/5/2022
@N.Kern 不,我没有设置它,我还有另一个页面我也没有设置它,但它确实显示错误很好..

答:

0赞 Ersin 3/11/2022 #1

下面的基本 php 代码应该为您提供表单提交过程的 3 种状态的想法,以正确调整您的代码。

  • 成功
  • 系统故障(例如,错误或临时服务器问题)
  • 输入的用户数据无效
    // data were valid && script's aim is achieved
    if (isset($_SESSION['state']) && $_SESSION['state'] == 1) {
        // your thanks/result page's content here;
        echo 'Thanks. Transaction was successful.';
        unset($_SESSION['state']);
        return; // not to continue
    }
    
    // form not submitted yet
    if ( false === (isset($_POST['submit']) && $_POST['submit'] = "your val")) {
        require 'form.php';
        return; // not to continue
    }
    // form submitted
    require 'validate.php'; // PHP codes to validate data from POST global var.
    // data are valid
    if (valid($_POST)) {
        // try what you aim with valid data
        require 'perform_aim.php';
        if (perform_aim_successful()) { // for example: record was inserted
            $_SESSION['state'] = 1; // success state
            header("Location: YOUR URL", TRUE, 301); // prevents reprocessing by F5 ($_POST is empty again by 301.)
            exit; // exit after a redirect
        }
        else {
            echo 'Your data was OK but script was failed. Try again later';
        }
    }
    // invalid data
    else {
        print_r($err_msgs); // error messages from/by 'validate.php'
        require 'form.php';
    }