user3636895
user3636895

Reputation: 41

How to stop the form input data from erasing after php validation invalid = true?

I have a form which the user enters data eg first name and last name etc. I have PHP validation which checks for empty field. The problem is when the submit button is clicked, the whole form data is erased when a field is left empty.

I tried this method below.

<input type="text" value="<?php echo $_POST["UserName"]; ?>"" name="UserName"   
id="UserName" size="20" /> 

But when the form loads for the first time, inside the text box is this

<br /><b>Notice</b>:  Undefined index: UserName in ...... on line <b>477</b><br />

Is there a method to stop the form from being cleared? or to echo the data into the fields?

Upvotes: 2

Views: 11893

Answers (6)

1keown
1keown

Reputation: 73

PHP forms will often discard entered data upon error validation, even when echoing it in the input field caches the entry on successful submit, and it is understandable that erasing disallowed data would be the default behavior. However, it can be a real hardship to retype large amounts of text in a textarea, and its sudden vanishing may come as an unwelcome surprise to the user, especially when due to a simple reason such as an over-the-character-number limit.

Setting the $_POST['UserName'] value with the error validation should preserve the field input without allowing its process. The example uses a variable to cache the data and echo it into the input field.

Update: The script has been updated to include multiple submit buttons for the same form, as well as the option for a success message array.

Update: The script has been updated to include an exit() option as well as a textarea.

  • UserName and First Name allowed characters are defined and will trigger an error with uppercase A-Z or special characters.

UserName uses the error array, while First Name uses exit() to stop the script altogether.

Textbox allowances also will trigger an error with uppercase A-Z or special characters, and use exit() to stop the script.

The form data will be preserved on error message, exit() page return, and successful send.

The form results are printed on successful send.

    <?php
    /* Define variables and set to empty values.*/
    $username=$first_name=$textbox='';
    /* If using non-array success variable, initialize it as a string:
    $success='';
    Otherwise, define as an array. */
    /* Submit button is clicked, start validation.
    Separate multiple submit buttons (for the same form) with || (|| = OR):
    */
    if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
    // Define error and success messages as arrays to display in a list.
    $error=array();
    $success=array();

    // Validate user input and error characters not lowercase a-z or 1-9.
    if (!empty($_POST['UserName'])) {
    /* Trim outside whitespace and sanitize user input.
    A custom function or purifier could well be used. */
    $username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
    if (preg_match("/^[a-z0-9]+$/", $username)) {
    /*
    if (preg_match("/^[a-z0-9]+$/", trim($_POST['UserName']))) {
    $username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
    }
    can be placed here instead, however input data will likely not be preserved on error. */
    // Data is acceptable, continue processing...
    }
    else {
    // Data is not accepted, set value to prevent loss on error and echo input without processing.
    $error[]='User Name can only contain lowercase a-z and 0-9.';
    $username=$username;
    /* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether:
    $username=$username;
    exit ("Username may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
    */
    }
    }
    else {
    $error[]="Please enter a User Name.";
    }

    if (!empty($_POST['first_name'])) {
    /* Trim outside whitespace and sanitize user input.
    A custom function or purifier could well be used. */
    $first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
    if (preg_match("/^[a-z0-9]+$/", $first_name)) {
    /*
    if (preg_match("/^[a-z0-9]+$/", trim($_POST['first_name']))) {
    $first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
    }
    can be placed here instead, however input data will likely not be preserved on error. */
    // Data is acceptable, continue processing...
    }
    else {
    // Data is not accepted, set value to prevent loss on error and echo input without processing.
    /* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
    $first_name=$first_name;
    exit ("First Name may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
    /*
    $error[]='First Name may only contain lowercase a-z and 0-9.';
    $first_name=$first_name;
    */
    }
    }
    else {
    $error[]="Please enter a First Name.";
    }

    if (!empty($_POST['textbox'])) {
    /* Trim outside whitespace and sanitize user input.
    A custom function or purifier could well be used. */
    $textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
    if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", $textbox)) {
    /*
    if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", trim($_POST['textbox']))) {
    $textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
    }
    can be placed here instead, however input data will likely not be preserved on error. */
    // Data is acceptable, continue processing...
    }
    else {
    // Data is not accepted, set value to prevent loss on error and echo input without processing.
    /* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
    $textbox=$textbox;
    exit ("Textbox input may only contain spaces, lowercase a-z, and 0-9. Use the Back-button to try again.");
    /*
    $error[]='Textbox input may only contain spaces, lowercase a-z, and 0-9.';
    $textbox=$textbox;
    */
    }
    }
    else {
    $error[]="Please enter Textbox content.";
    }

    // If no errors, process data.
    if (empty($error)) {
    if (isset($_POST['submit_one'])) {
    /* Sanitized submit button per rule #1: never trust user input. Remove sanitization if it causes a system error.
    Reiterating ($_POST['submit'] is helpful when using multiple submit buttons.
    Wrap each function in the additional submit isset, and end functions with closing (empty($error) else statement. */
    $_POST['submit_one']=trim(htmlspecialchars($_POST['submit_one'], ENT_QUOTES));
    /* Post data or send email, and print success message.
    The array is option. Do not define as an array or use[] to use as a simple variable. */
    // Processing data here, for example posting to a database ...
    $success[]="The submit_one Send Form request has been processed!";
    }

    if (isset($_POST['submit_two'])) {
    $_POST['submit_two']=trim(htmlspecialchars($_POST['submit_two'], ENT_QUOTES));
    // Processing data here, for example sending an email ...
    $success[]="The submit_two Process Form request has been sent!";
    }
    }
    /* If errors, show error message.
    The exit() option ends the script at the validation check .*/
    else {
    $error[]="Please correct the errors and try again.";
    }
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <style type="text/css">
    .wrapper {margin: 2% auto; width: 500px;}
    textarea {text-align:left;}
    </style>
    </head>

    <body>
    <div id="anchor" class="wrapper">
    <div>
    <form name="data_form" action="#anchor" method="post">
    <table>
    <tr>
    <td colspan="2">
    <label for="UserName">User Name</label>
    <br>
    <input type="text" name="UserName" id="UserName" size="20" value="<?php echo $username; ?>" />
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <label for="first_name">First Name</label>
    <br>
    <input type="text" name="first_name" id="first_name" size="20" value="<?php echo $first_name; ?>" />
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <label for="textbox">Textbox</label>
    <textarea name="textbox" id="textbox" style="height:100px; width:98%;text-align:left;"><?php echo $textbox; ?></textarea>
    </td>
    </tr>
    <tr>
    <td>
    <input type="submit" name="submit_one" id="submit_one" value="Send Form">
    </td>
    <td>
    <input type="submit" name="submit_two" id="submit_two" value="Process Form">
    </td>
    </tr>
    </table>
    </form>
    </div>
    <div>
    <?php
    /* Print errors as a list or print success message.
    Separate multiple submit buttons with ||. */
    if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
    if (!empty($error)) {
    echo '<h4>The form was not sent due to the following errors:</h4>
    <ul>';
    foreach ($error as $message) {echo '<li>'. $message . '</li>';
    }
    echo '</ul>';
    }
    /* Print success confirmations as a list for processed input. */
    else {
    echo '<h4>The form has been sent!</h4>
    <ul>';
    foreach ($success as $message) {echo '<li>'. $message . '</li>';}
    /* If using a success variable without defining it as an array,
    initialize it as a variable at the top of the script,
    then print variable without <ul>s and foreach loop:
    echo '<p>' . $success . '</p>';
    */
    echo '</ul>
    <h4>Processed Data:</h4>
    <ul>
    <li>User Name: ' . $username . '</li>
    <li>First Name: ' . $first_name . '</li>
    <li>Textbox: <br>' .
    /* Replace $textbox new lines with <br> tags. */
    nl2br($textbox) .
    '</li>
    </ul>';
    }
    /* Unset foreach loop data. */
    unset($message);
    }
    ?>
    </div>
    </div>
    </body>
    </html>

Upvotes: 0

fin
fin

Reputation: 333

The issue here is that you're not checking whether $_POST["UserName"] is initialized, and when it is not, you'll throw the error. Check with isset:

   <input type="text" value="<? if isset($_POST["UserName"]) { echo $_POST["UserName"]; } ?>" name="Givenname" id="Givenname" size="20" /> 

Upvotes: 2

nl-x
nl-x

Reputation: 11832

Your form is not being cleared or erased. But you are loading a NEW page with a NEW form.

Your attempt to load the new form is a good one, but you need to change

<input type="text" value="value="<?php echo $_POST["UserName"]; ?>"" name="UserName"    id="UserName" size="20" />

into

<input type="text" value="<?php echo isset($_POST["UserName"])?$_POST["UserName"]:""; ?>" name="UserName" id="UserName" size="20" /> 

So remove the second value=" and the corresponding " which should have never been there. And check if the variable is available before trying to echo it.

In addition to doing this, you might also want to do client side validation in Javascript on top of the server side validation. (Never only do client side validation, by the way, as that can be fooled by end users.)

What you can do is to change your <form> tag into this:

<form action="..." method="post" onsubmit="if (document.getElementById('UserName').value == '') { alert('UserName is still empty'); return false; }">

This will prevent the form from being sent to PHP when UserName is still empty. And thus prevent from the page being reloaded and the form being cleared.

Upvotes: 1

Aiswarjya
Aiswarjya

Reputation: 217

I think you are using Reset button like this:

<input type="reset" />

Try this:

<input type="submit" />

If you are trying Second one then use required in every input like:

<input required type="text" />

Upvotes: 1

Mifmif
Mifmif

Reputation: 3190

replace this :

value="<?php echo $_POST["UserName"]; ?>"

in your code with this :

<?php if(isset($_POST["UserName"])) echo $_POST["UserName"]; ?>

Upvotes: 5

Manoj Yadav
Manoj Yadav

Reputation: 6612

Check if $_POST["UserName"] isset, Try this:

<input type="text" value="<?php echo isset($_POST["UserName"]) ? $_POST["UserName"] : ''; ?>" name="Givenname"   
id="Givenname" size="20" /> 

Upvotes: 1

Related Questions