Form Validation with PHP and Javascript: No Refreshes

This is a repost of one I did a while ago and deleted, but I like it so I’m going to post it again!

I was fooling around with CSS and Javascript and eventually started to mix the two into PHP. Using two frames, one spanned 100% of the page (thus, it’s like there is no frame) and the other one just there to load new bits of Javascript. The form posts data to the other frame, which is a PHP script, and PHP works out Javascript depending on the information it received. Within the HTML form (the main frame), we have hidden div’s that contain error messages, when PHP find something that doesn’t validate, we output Javascript to un-hide those div’s and thus display the error messages. Look at the bottom of this post for a working example.

We’ll use a user sign up form throughout this post to demonstrate. It’s really quite nifty :-D

We’ll start off with a standard frameset. Like I already said, the main frame can take up the entire screen, so the user never needs to know it was there.
[code lang="xml"]





[/code]
Note that I made the main frame 90% instead of 100%. This way you can see the output that PHP makes by right-clicking the frame and “view source”.

Next there’s the HTML form, which in the frameset I’ve called ‘html.html’ (how original!):
[code lang="xml"]




Account Information

Username

Alphanumeric, 10 char max and 3 char min.

Password

3 char min.

Email

Must be valid email address

Comments

255 chars max


Continue


[/code]

There’s some useless CSS and JS in there that makes the form elements highlight when you hover over them, you can ignore those bits (like I said, I was fooling around ;-)). The most important parts are the error divs, which are of class ‘error’. In this script, their ID must be “error_x”, where X is the name of the form field. For example:
[code lang="xml"]

Username
id=”error_username” class=”error” style=”display:none”>
name=”username” style=”width:80%” />

Alphanumeric, 10 char max and 3 char min.

[/code]
The field name is ‘username’, thus the ID of the error div has to be ‘error_username’. If you had a field named ‘i_hate_fish’, the error div would be ‘error_i_hate_fish’. Of course you could always alter the PHP script to give whatever names you wanted, but I find it easiest this way. Also note the style display property is set to ‘none’. We want it to remain hidden until the user has an error with a particular form field.

The next thing to notice is the form’s action, target and id:
[code lang="xml"]

[/code]
The action is the special validation PHP script that we’ll talk about in a moment, and the target is the special (usually hidden) frame we have set up. Make sure you keep the form ID as well. We need to alter the form action and target if the user has filled in correct info, and to do that we need to access it from the other frame. If you’re going to change the id of the form, make sure you change it in the validate.php script as well.

Now on to the good bits! The validation script:
[code lang="php"]



function getInvalid($array)
{
$invalid = array();

foreach($array AS $k => $v)
{
$v = urldecode($v);

$okay = true;
switch($k)
{
case ‘username’:
if(!preg_match(’#[a-zA-Z0-9-_]{3,10}#’, $v))
$okay = false;
break;

case ‘email’:
if(!preg_match(’#^([a-zA-Z0-9_-.]+)@([a-zA-Z0-9_-.]+).([a-zA-Z]{2,5})$#’, $v))
$okay = false;
break;

case ‘password’:
if(strlen($v) < 3)
$okay = false;
break;

case 'comments':
if(strlen($v) > 255)
$okay = false;
break;

default:
unset($okay);
break;
}

if(isset($okay))
$invalid[$k] = $okay;
}

return $invalid;
}

function writeJS($item, $okay)
{
echo “error_$item = getItemMain(’error_$item’);n”;
echo “if(error_$item) {n”;

if(!$okay)
echo “error_$item.style.display = ”;n”;
else
echo “error_$item.style.display = ‘none’;n”;

echo “}nn”;

}

?>[/code]
(Note, I have a hidden form element ‘do’ in the HTML that holds no particular value, but in the PHP script it checks to make sure it exists before continuing. I did this to make sure the script didn’t function the the frame was first loaded. You could always just make the source of the frame empty, or check for the submit button instead. But I’m too lazy to change it :-P).

We have an array, $invalid, that holds the status of all the form fields. If a field is correct, then the $invalid array index for that field holds true, and if it is invalid, it holds false.

The next bit of Javascript code is just a method to get object from the ‘main’ frame by using it’s ID. It’s a modified version of my ‘getItem’ function I use a lot.

After that, we get PHP to loop through all the items in $invalid and then call a PHP function writeJS() to write the proper JS for it. If the item is false (or the field is invalid), then the JS outputted makes the error div on the main frame visible. If it’s true, then the JS makes the error div hidden. Simple as that!

Then finally after all that, we get PHP to check if there were any invalid form fields (using in_array(), checking for false within $invalid). If there isn’t, then we output some JS to change the action and target to the “real” form handler, then we fire up the submit() event to submit the form.

Hopefully I explained that well enough! As promised, here is the working example: clickety.

2 Responses to “Form Validation with PHP and Javascript: No Refreshes”

  1. Erick Says:

    i had a question about this page.

    http://www.chroder.com/index.php?p=6

    i want to set the default state of a table to start out not showing, without using cookies (which i dont understand) or anything too special. how would i go about doing that?

    thanks a lot btw

  2. Chris Says:

    To start it out not showing, just add style=”display:none” to each thing you want to be hidden (the tbody’s).

Leave a Reply