Forum Moderators: open

Message Too Old, No Replies

Error checking using a combination of PHP and JavaScript

I want to highlight invalid fields and retain the values for other fields

         

dougmcc1

1:18 am on Jan 10, 2004 (gmt 0)

10+ Year Member



I have a form that sends variables to a PHP script which does error checking to make sure the values entered are valid. If not, the script outputs an error message and offers an input button for the user to click in order to return to the form with all the values he/she entered still intact. I do this using onClick="history.go(-1); return false".

When an invalid value is submitted from the form, the name of the input field is entered into a variable called $error_field.

What I want to do is send the value of the variable back to the form and use it to highlight the background color of the input field that the user entered the invalid value into, or maybe display a red asterisk or something to that effect...

Here is the code for the form page:
<html>
<head>
<?
if ($error_field) {
echo "<script type='text/javascript'>\n
document.TheForm.$error_field.style.backgroundColor='#ff0000';\n";
}
?>
</head>
<body>
<form name=TheForm method=post action=script.php>
<input name=FirstField>
<input name=SecondField>
<input type=submit value=Submit>
</form>
</body>
</html>

Here is the code for the script:
<?
if (!$FirstField) {
$error_field="FirstField";
die("
<form method=post>\n
You didnt enter a value into the FirstField field.\n
<input type=hidden name=error_field value=$error_field>\n
<input type=submit value=OK>\n
</form>
");
} else if (!$SecondField) {
$error_field="SecondField";
die("
<form method=post>\n
You didnt enter a value into the SecondField field.\n
<input type=hidden name=error_field value=$error_field>\n
<input type=submit value=OK>\n
</form>
");
}
?>

Thanks in advance.

Purple Martin

12:41 am on Jan 14, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



So when there's an invalid entry, you serve a new page with a button to return to the form? Sounds to me like you'd be better off just serving the form again, with all the info they'd entered put back in the fields for them. At the same time you'd also be able to set the colour of the field on the fly (or change the coulour of the field's label, or add a red asterisk, or whatever) with php.

dougmcc1

7:19 am on Jan 14, 2004 (gmt 0)

10+ Year Member



Yeah, you're right, it would make more sense to re-serve the form page to them again. I'll try that route. Thanks.