PHP tutorials
Question:
How do I put an error message next to a form element if the field was incorrectly filled in (or not filled in)?
Answer:
If a form on the web is filled out incorrectly quite often a mark is placed next to the item requiring further attention. This is often done with a red asteriks or explanation mark, and only requires slight modification to the sticky forms technique.
Additional Notes
See the entire source code for this example. more
See a working website with this code. more
Example
The example code demonstrates the technique for the edit field, however the technique can easily be applied for all types of input controls. The source comments explain the process involved.
...
//-----
//First we check that the submit button has been pressed. If it has
//then we process the form elements, starting with the text-input
//field. If the room-number has not been set, then we set $RN to
//false. (Make sure we initialize the variables)…
//-----
$RN = '';
...
if(isset($_POST['submit']))
{
//process the text-input field
if(isset($_POST['roomnumber']) && is_numeric($_POST['roomnumber']))
$RN = (int)$_POST['roomnumber'];
else
$RN = false;
...
//-----
//when it comes time to display the room-number label we check if
//the submit button has been pressed and that $RN is false. This
//means that there is a problem with the Room-Number field
//element, and we can adjust the display.
//-----
//display text-input label for room-number
if(isset($_POST['submit']) && !$RN)
echo '<p><font color="red" size="+1"><b>! Room Number</b></font><br />';
else
echo '<p>Room Number<br />';
//display the text-input field
echo '<input type="text" name="roomnumber" maxlength="60" size="60"
value="' . $RN . '" /></p>';
...
PHP Reference Manual
$_POST - POST array containing form elements and values
isset - Checks to see if a variable is set
is_numeric - Checks to see if a variable is numeric
Comments or questions relating to this article have been disabled. They will be back soon.
Copyright
Let notice be given that this is copyright information