Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking fields are not left empty

Status
Not open for further replies.

waydown

Programmer
Apr 27, 2009
49
0
0
GB
Hi,
I have a form validation and then the form.
<?php
if ( isset($_POST['submitted'])
{ if ($_POST[name])
{ $name = $_POST[name];
}
else
{ //what code goes here?
}
}

<form name="A.php" action="" method="post">
......
<input type="text" name="name" id="name" />
....
<input type="text" name="email" id="email" />
....
</form>
?>

What I would like to happen in the else statement is that if name field is left blank user is automatically redirected to the name field which should be highlighted and a small error message that the name field was left empty should appear. What would be the code for that? I would be very grateful for all help.
 
google php form validation

but essentially there is no automated method - you have to use a framework (such as quickform) or roll your own. for you this may suffice

Code:
<?php
if ( isset($_POST['submitted'])
{  if ($_POST[name])
   {  $name = $_POST[name]; 
    }
    else
   { 
     $nameStyle = 'highlight';
     $nameMessage = 'You must include a name';
   }
}
<style type="text/css">
input .highlight { background-color: yellow; }
</style>

<form name="A.php" action="" method="post">
......
<input type="text" name="name" id="name"  class="<?php  echo isset($nameStyle) ? $nameStyle : '';?>" /><br />
<?php echo isset($nameMessage) ? $nameMessage . "<br/>": '';?>
....
<input type="text" name="email" id="email" />
....
</form> 
?>
 
Hi jpadie,
Many thanks for your solution, it worked nicely for me. I would like to ask why the solution you gave me does not work for:
<input type="file" name="picture" id="fileUpload"
accept="image/gif, image/jpeg, image/png" />
I've tried writing:
<?php
if ( isset($_POST['submitted'])
{ if (isset($_POST['picture']))
{ //do something
}
else
{
$fileMessage = 'You must upload an image';
}
}
.........

<input type="file" name="picture" id="fileUpload"
accept="image/gif, image/jpeg, image/png" />
<?php echo isset($fileMessage) ? $fileMessage . "<br/>": '';?>

There must be something wrong with my code because the error message does not appear. Again many thanks for your help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top