Hi I seem to be lost with this form validation
When submited empty the error should display next the input field in red.
Thanks in advance
D
<?php
if (array_key_exists('submit',$_POST)){
//Form has been submitted
// Fields that are on form
$expected = array('name', 'email', 'comments');
// Set required fields
$required = array('name', 'comments');
// Initialize array for errors
$errors = array();
foreach ($_POST as $field => $value){
// Make sure field was done correctly otherwise add error.
}
// Assign to $temp and trim spaces if not array
$temp = is_array($value) ? $value : trim($value);
// If field is empty and required, tag onto $errors array
if (empty($temp) && in_array($field, $required)) {
array_push($errors, $field);
}
if (empty($errors)){
//The form is completed properly to do with as you please
unset($errors);
}
}
?>
<html>
<head>
<title>Form</title>
<link rel="stylesheet" type="text/css" href="assets/css/default.css">
</head>
<body>
<div id="content">
<form id="commentform" method="post" action="index.php">
<p>
<label for="name">Name:</label> <?php if (isset($errors) && in_array('name', $errors)){?> <div class="red">Please enter name</div> <?php } ?>
<br/>
<input name="name" id="name" type="text" <?php if (isset($errors)) { echo 'value="'.htmlentities($_POST['name']).'"'; } ?> />
</p>
<p>
<label for="email">Email:</label> <br/>
<input name="email" id="email" type="text"/>
</p>
<p>
<label for="comments">Comment:</label>
<br/>
<textarea name="comments" id="comments" rows="4"><?php if (isset($errors)) { echo htmlentities($_POST['comments']); } ?>