简体   繁体   中英

The PHP form action is located on another page! how to validate the form and show the error message on the view page?

I have two files, the first one is for displaying a form(HTML), and the second one is for the form action(PHP Code). I made a simple validation code but it shows me an error message like the image below.

在此处输入图像描述

view.php

<form action="redirect.php" method="POST">
<input type="text" id="name" name="name" value="" />
<span style="color: red;"><?php echo $nameError;?></span>

<button type="submit">Submit</button>
</form>

redirect.php

<?php

require "db.php";

// Initialize variables to null.
$nameError ="";

// On submitting form below function will execute.
if (isset($_POST["submit"])) {
    $name = $_POST["name"];
    
    if(empty($name)) {
        $nameError = "Name is required";
    }
}

?>

Because you defined the nameError variable in the redirect.php but you want to use it in view.php .

There are several solutions:

1: Move your validation code to the top of view.php .

2: Pass the nameError content into $_SESSION global array. eg: $_SESSION['nameError'] = "Name is required"; And modify validation to `

if(empty($name)) {
    $_SESSION['nameError'] = "Name is required";
    header("Location: view.php");
    exit;
}`

And change code in view.php from <span style="color: red;"><?php echo $nameError;?></span> to

<?php if(isset($_SESSION['nameError'])): ?>
<span style="color: red;"><?php echo $_SESSION['nameError'];?></span>
<?php endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM