Jump to content

Working with PHP and the $_POST array


rockinaway

Recommended Posts

I have a form, and when the user submits it, there are a variety of checks in PHP to see if the values are correct. If not, the page is returned with errors.

 

What I want to do is also edit the form fields which have the errors. So for example if $_POST['field'] had an error, then on the page reload I would want the border of the form field to be red.

 

I guess this will use Javascript.. any ideas how it would work?

Link to comment
Share on other sites

Well you guys have the right idea in that it can be done entirely with php, however this talk of td tags for markup that is not tabular (its a form) and bordercolor is so outdated it wont even validated with any doctype!

 

To do this, first off set a CSS class:

 

.warning
{
    border: solid 1px #DD6500;
}

 

Then, add that class to the input in question:

 

echo "<input type=\"text\" name=\"field\"";
if(isset($_POST['field']))
{
    echo " class=\"warning\"";
}
echo " />

 

The if statement checks to see if the form has been submitted and come back to here. If it has, then it makes the input have the class 'warning' (this class wont be attached if the form hasn't been submitted). This class surrounds anything its attached to with a solid red border 1px in width.

 

As the code stands now, it will add the border after the form has been submitted, whether the data inside the field is wrong or not. So if the incorrect data is in a different field, this field will still have a red border. As such, you will have to add an extra check to see if the data is incorrect or not. I would suggest that when you do the check to see if the data inside is ok, if it fails that check, set a variable with some name. Then where I checked to see if the data had been posted, instead check to see if that variable has been set. If it has, then attach the class name. If it hasn't, then don't attach the class name.

 

Lastly, don't name the class something like 'red' - you may want to change the color sometime in the future, and having a class named 'red' that sets a blue border will be a little misleading to say the least.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.