Here's a script you might be able to work from:
$input = array('name' => '', 'id' => '');
if (!isset($_POST['submit'])) {
echo form($input);
} else {
$error = false;
if (!valid_name($_POST['name'])) {
$error = true;
$name = 'error';
} else {
$name = $_POST['name'];
}
if (!valid_id($_POST['id'])) {
$error = true;
$id = 'error';
} else {
$id = $_POST['id'];
}
if ($error) {
$input['name'] = $name;
$input['id'] = $id;
echo form($input);
} else {
echo 'Your input is accepted.<br />';
echo $name . '<br />';
echo $id . '<br />';
}
}
function form($array)
{
$ret = '<form action="' . $_SERVER['PHP_SELF'] .
'" method="post">';
$ret .= input_line($array['name'], 'name', 'Name');
$ret .= '<br />';
$ret .= input_line($array['id'], 'id', 'ID #');
$ret .= '<br /><input type="submit" name="submit" ' .
'value="submit" />';
$ret .= '</form>';
return $ret;
}
function input_line($data, $key, $label)
{
if ($data == 'error') {
$color = 'red';
$value = '';
} else {
$color = 'black';
$value = $data;
}
$ret = '<font color="' . $color . '">' . $label .
': </font>';
$ret .= '<input type="text" name="' . $key .
'" value="' . $value . '" />';
return $ret;
}
function valid_name($name) {
if (strlen($name) < 5) {
return false;
} else {
return true;
}
}
function valid_id($id) {
if (!is_numeric($id)) {
return false;
} else {
return true;
}
}
It's not perfect, of course; the logic could be tightened, styles could be used, it might be better as a class because of function/variable interdependence, etc. But maybe it will help.
There's a good article on form error handling here (although I'm not fond of the coding style 🙂 ).