Form Input Required Fields Errors
Posted: Tue Aug 17, 2010 2:17 am
I built a basic form that requires certain fields to be filled. I also have errors ready to be echoed out incase these fields are not filled. However, the echoed errors appear above the form. I'd like to get more detailed and place each error underneath its respectable form field if the field isn't filled.
Ideally I'd like to use Ajax to echo the errors asynchronously but I definitely want to take steps and understand how to output errors in specific areas first.
Ideally I'd like to use Ajax to echo the errors asynchronously but I definitely want to take steps and understand how to output errors in specific areas first.
Code: Select all
<?php
if(!empty($_POST['submit']))
{
// set variables
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$email2 = mysql_real_escape_string($_POST['email2']);
$age = mysql_real_escape_string($_POST['age']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
// 1A. REQUIRED FIELDS VERIFICATION
if(!empty($name) && !empty($email) && !empty($email2) && !empty($city) && !empty($state))
{
// 1B. END REQUIRED FIELDS VERIFICATION
} else {
echo '<img src="images/icon_error.png" alt="" title="" /> Please fill out the required fields.<br />';
if (empty($name))
{
echo 'Whats your name?!<br />';
} if (empty($email))
{
echo 'No email given.<br />';
} if (empty($email2))
{
echo 'Please verify your email<br />';
} if (empty($city))
{
echo 'What city are you from?<br />';
} if (empty($state))
{
echo 'What State!<br />';
}
echo '<br /><br />';
}
// 1B. END REQUIRED FIELDS ERROR CODES
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<div class="formSec"><label for="name" class="required">Full Name:</label>
<input type="text" name="name" id="name" value="" /></div>
<div class="formSec"><label for="email" class="required">Email:</label>
<input type="text" name="email" id="email" value="" /></div>
<div class="formSec"><label for="email2" class="required">Confirm Email:</label>
<input type="text" name="email2" id="email2" value="" /></div>
<div class="formSec"><label for="age" class="required">Age:</label>
<input type="text" name="age" id="age" value="" /></div>
<div class="formSec"><label for="city" class="required">City:</label>
<input type="text" name="city" id="city" value="" /></div>
<input class="submit" type="submit" name="submit" value="Submit" />
</form>