Hello,

So I have a PHP page where I can enter my name, address, phone #, etc. I have some of these fields designed to be required information. If I do not enter something in the required fields, then information I have in other fields are lost when I submit the information.
For instance let's say "Name", "Address", and "Phone number" are set as required fields, If I were to enter my name and address, but not my phone number and submitted the information, the page would refresh and display "Each field is required", however the fields marked name and address would be empty. How do I prevent that from happening?

Recommended Answers

All 8 Replies

I don't have an exact answer my friend but I might be able to push your search into the right direction. Usually this type of behaviour is down to the clients browser, therefore I would suggest looking at JavaScript which is all executed client side. Perhaps looking into the onkeyup event to detect and collect user data and then store the data in a cookie? It's a rough answer and maybe someone here can really push you in the best direction - that's just my input.

I pulled this answer from a user called arthurr on StackOverflow:

I had similar issue at one of my project so I wrote some js to handle this using cookies. First I found two simple functions to set and get cookies values:

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
  {
  c_start = c_value.indexOf(c_name + "=");
  }
if (c_start == -1)
  {
  c_value = null;
  }
else
  {
  c_start = c_value.indexOf("=", c_start) + 1;
  var c_end = c_value.indexOf(";", c_start);
  if (c_end == -1)
  {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}

Than I wrote two other functions to set and get input values:

function saveValue(input) {
    var name = input.attr('name');
    var value = input.val();
    setCookie(name,value);
}

function getValue(input) {
    var name = input.attr('name');
    var value = getCookie(name);
    if(value != null && value != "" ) {
        return value;
    }
}

And using jQuery I save user's input value to session cookie

$('input[type=text]').each(function(){
        var value = getValue($(this));
        $(this).val(value);
    }).on('blur', function(){
        if($(this).val() != '' ) {
            saveValue($(this));
        }
    });

I hope it'll help ;)

Good luck!

<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
<input type='text' name='firstname' value='<?php if(isset($_POST['firstname'])){echo $_POST['firstname'];} ?>'><label for='firstname'>First Name</label>

@almostbob - how is this going to repopulate fields on a page refresh?

Why not using directly sessions ? On submit, save each value of the inputs in a different session. If a field is empty, we can redirect the user to the form - but this time we can auto-complete the other inputs using the data provided last time (which was stored in the sessions).

Probably something like this (not tested) :

<?php if (isset($_SESSION["name"]) && !empty($_SESSION["name"])) : ?>

    <input type=text value="<?php echo htmlspecialchars($_SESSION["name"]); ?>"/>

<?php else : ?>

    <input type=text value="Please complete this field."/>

<?php endif; ?>

Blikin' hell I totally misunderstood the question haha, sorry!

On form submission you could create a session for each of the fields before processing and then simply unset/destroy the sessions at the end of processing.

I.E:

if(isset($_POST['forum_submit'])){

    //Create session for each field
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['firstname'] = $_POST['firstname'];
    // and so forth...

{

and then for each field:

<input name="username" type="text" value="<?php if(isset($_SESSION['username'])){echo $_SESSION['username'];} ?>">

Therefore if a session exists that holds form data it'll be entered as input field values.

For instance let's say "Name", "Address", and "Phone number" are set as required fields, If I were to enter my name and address, but not my phone number and submitted the information, the page would refresh and display "Each field is required", however the fields marked name and address would be empty. How do I prevent that from happening?

I'm not sure if I missed something here, but I dont see any recommendations for validating client side before allowing a post back to occur. Of course I understand that you should also validate server-side to make sure that the client side validation wasnt bypassed, but why bother making a trip to the server if you can check these values client-side first?

I agree with jorgeM

an example:

<html>
<head>
<script>
function validate()
{
if (document.forms["frm"]["name"].value)
    {
    alert("Welcome " + document.forms["frm"]["name"].value + "!")
    return true; // form will submit
    }
else 
    {
    alert("no user");
    return false; // form will not submit       
    }
}
</script>
</head>
<body>

What is your name?<br>
<form name="frm" action="submit.htm" onsubmit="return validate();">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>

</body>
</html> 
Member Avatar for diafol

Your approach needs to be two-fold, as mentioned by contributors thus far.

  1. Enable users to get immediate feedback from client-side validation (javascript), so that they do not send the form with invalid data in the first place. Some will not have js enabled of course. There are plenty of examples to be had online.

  2. Your server-side validation routine needs to capture all the fields and place them into a session array variable which can be returned to the form page. This variable should then be killed once the info is extracted from it. Repopulate the various form fields. You can use additional info from the validation, e.g. an error variable or item in the session to place an error message (inline or in a section) on the form page.

Example PHP (quick and dirty)

session_start();

$formExpectedData = array(
    'key1' => array('required' => true, 'type' => 'int', min => 10, max => 25, 'err_msg' => 'Your value for key1 must be between 10 and 25'),
    'key2' => array('required' => false, 'type' => 'string', min=>0, max=>32, 'err_msg' => 'If you provide key2, it must have a maximum of 32 characters...'),
    //...etc...//  
);

if(isset(!$_POST['some_field']))
{
    $result = array();
    $error = false;
    foreach($_POST as $key=>$value)
    {
        $result[$key] = validate($key, $value, $formExpectedData[$key]);
        if($result[$key]['error']) $error = true;
    }
    if($error)
    {
        $_SESSION['form_error'] = $result;
        header('Location: formpage.php');
        exit;
    }
}

The validate function checks each item value against expected/allowed data. That's a very rough example. You'll have a much better validation array structure I'm sure.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.