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

10,463

Solution 1

replace this :

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

in your code with this :

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

Solution 2

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" /> 

Solution 3

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.

Solution 4

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

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

Solution 5

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" />
Share:
10,463
user3636895
Author by

user3636895

Updated on June 15, 2022

Comments

  • user3636895
    user3636895 almost 2 years

    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?