Jump to content

How to echo an error message next to a form field


redrabbit

Recommended Posts

Ok this is the code below for validating the first name and last name of someone who enters data into the form, lets say they are both required, so the user needs to be informed when he leaves one blank, how do I echo the error message to the user in the HTML next to the input field saying firstname or lastname was left blank?

 

if (empty($fname)) {
		echo 'Please enter your firstname';
		$error = true;
		$output_form = true;
	}

	if (empty($lname)) {
		echo 'Please enter your surname';
		$error = true;
		$output_form = true;
	}

 

 

The html part of the form is:

 

<tr>			   
		<th>First Name:</th>
					<td>
						<input type="text" name="firstname" class="medium" value= "<?php  if (!empty($fname)) echo $fname; ?>" />
					</td>	
				</tr>


				<tr>
					<th>Surname:</th>
						<td>
							<input type="text" name="surname" class="large" value="<?php  if (!empty($lname)) echo $lname; ?>" />
						</td>
				</tr>

I usually would do this...

if (empty($fname)) {
         $errors['firstname'] = 'Please enter your firstname';
         $error = true;
         $output_form = true;
      }
         
      if (empty($lname)) {
         $errors['surname'] =  'Please enter your surname';
         $error = true;
         $output_form = true;
      }

 

<tr>            
         <th>First Name: <?php $errors['firstname'] ?></th>
                  <td>
                     <input type="text" name="firstname" class="medium" value= "<?php  if (!empty($fname)) echo $fname; ?>" />
                  </td>   
               </tr>


               <tr>
                  <th>Surname: <?php $errors['surname'] ?></th>
                     <td>
                        <input type="text" name="surname" class="large" value="<?php  if (!empty($lname)) echo $lname; ?>" />
                     </td>
               </tr>

 

Or alternatively, is putting it on the end of the field itself.

ex:

<input type="text" name="surname" class="large" value="<?php  if (!empty($lname)) echo $lname; ?>" /><?php $errors['surname'] ?>

 

Although the if !empty part, you don't really need, because if its empty.. nothing will get outputted in. It'll issue a warning, but with errors turned off you won't see it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.