Jump to content

Add Form Errors beside Label/Input on Page?


mfleming

Recommended Posts

Hello.

 

I have a basic form and I want to check for errors by making sure the user inputs everything, if not an error explaining to the user what needs to be fixed. (very common on all forms)

 

When I use echo in my script, it displays at the top of my browser.  How do I put the error codes right beside my form elements?

I currently don't have all the error checking included but I want to get a few sorted out before anything else.

 

Form Page:

http://www.fusionfashionhair.com/registration.php

 

My PHP Code all above DOCTYPE in the php file.

<?php 
$submit = $_POST['submit'];
// Form Data
// Check all form inputs using check_input function
$name = strip_tags($_POST['name']);
$address = strip_tags($_POST['address']);
$email = strip_tags($_POST['email']);
$repeatemail = strip_tags($_POST['repeatemail']);
$phone = strip_tags($_POST['phone'], "Enter your Phone Number");
$salonname = strip_tags($_POST['salonname']);
$salonaddress = strip_tags($_POST['salonaddress']);
$salonprov = strip_tags($_POST['salonprov']);
$salonpostal = strip_tags($_POST['salonpostal']);
$salonconfirm = strip_tags($_POST['salonconfirm']);
$enewsletter = strip_tags($_POST['enewsletter']);
$saloncountry = strip_tags($_POST['saloncountry']);
$password = strip_tags($_POST['password']);
$repeatpassword = strip_tags($_POST['repeatpassword']);
$date = date("Y-m-d");
// Set e-mail recipient
$myemail = "info@fusionfashionhair.com";


if ($submit)
{
    //check for existance
    if ($name&&$password&&$repeatpassword&&$email)
    {
        if ($password==$repeatpassword)
        {
            if ($email==$repeatemail)
            {    
                //check password length
                if (strlen($password)>32||strlen($password)<6)
                {
                    echo '<p class="formecho">Password must be between 6 and 32 characters</p>';
                }
                else
                {
                    // Thank you Page
                    $insertGoTo = "thankyou.php";
                    header(sprintf("Location: %s", $insertGoTo));
                    
                    // encrypt password
                    $temppass = $password;
                    $password = md5($password);
                    $repeatpassword = md5($repeatpassword);
                    
                    // dBase file
                    include "dbConfig.php";
                    //open database
                    //generate random number for activation process
                    $random = md5(rand(23456789,987654321));
                    
                    
                    // register the user!                
                    // Set default username
                    $username = $email;
    
                    // INSERT INTO user...  replace user with table name
                    // make sure you have the same number and order of values as the database has
                    $queryreg = mysql_query("
                    
                    INSERT INTO user VALUES ('','$name','$username','$password','$date','$email','$phone','$address','$salonname','$salonaddress','$salonprov','$salonpostal','$saloncountry','$salonconfirm','$enewsletter','$random','0')");
                    
                    //Insert ID based on last ID in database
                    $lastid = mysql_insert_id();
                    
                    //send activation email
                    $to = $email;
                    $subject = "Activate Salon Member Acctount at Fusion Fashion Hair";
                    $headers = "From:  webmaster@fusionfashionhair.com";
                    $server = "mail.fusionfashionhair.com";
                    
                    //change php.ini and set SMTP to $server
                    ini_set("SMTP",$server);
                    
                    
                    $body = "
                    
                    $name from $salonname is wanting a membership, \n\n
                    
                    Please click on the link provided below to activate the account with Fusion Fashion Hair
                    http://www.fusionfashionhair.com/activate.php?id=$lastid&code=$random \n\n
                    
                    Username = $username \n
                    Password = $temppass \n
                    
                    
                    Thank you,
                    
                    Customer Service
                    ";
                    
                    //function to send email
                    mail($to, $subject, $body, $headers);
                    
                }
            }    
        else
        echo '<p class="formecho">Your passwords do not match!</p>';
        }
        else
        echo '<p class="formecho">Your Emails do not match!</p>';
    }//End check Existance
    else
        echo '<p class="formecho">Please fill in <b>ALL</b> fields!</p>';
}// End if Sumbit

?>

 

Link to comment
Share on other sites

Can't give you a specific example because the code for your form is not present. In general, you accomplish this by modifying the code that writes the form to the browser to include the errors. In order to check for errors somewhere else and know what errors to print, you need to save the relevant errors to a variable (usually an array) and then, when PHP is writing the form, check the array to see if that particular element has an error (and if it does, show the error message next to the element in error, if it doesn't, just write the normal form code for that element).

Link to comment
Share on other sites

I know what I want to do I just don't know the code to do it.

 

My form Code:

    <form action='registration.php' method='post' id="regform">
      <fieldset>
        <legend>Personal Information</legend>
        <p> </p>
        <p>
          <label for='name'>Name:</label>
          <!--using the value = and php echo you can store the value in the forms without re-entering the values-->
          <input name='name' type='text' value='<?php echo $name; ?>' maxlength="25"/>
          <span class="required">*</span><br />
        </p>
        <p>
          <label for="address">Address: </label>
          <!--using the value = and php echo you can store the value in the forms without re-entering the values-->
          <input name='address' type='text' value='<?php echo $address; ?>' maxlength="25"/>
          <span class="required">*</span><br />
        </p>
        <p>
          <label for="email">Email: </label>
          <!--using the value = and php echo you can store the value in the forms without re-entering the values-->
          <input name='email' type='text' value='<?php echo $email; ?>' maxlength="25"/>
          <span class="required">*</span><br />
        </p>
        <p>
          <label for="repeatemail">Confirm Email:</label>
          <input type='text' name='repeatemail' />
          <span class="required">*</span><br />
        </p>
        <p>
          <label for="phone">Phone: </label>
          <!--using the value = and php echo you can store the value in the forms without re-entering the values-->
          <input name='phone' type='text' value='<?php echo $phone; ?>' maxlength="14"/>
          <span class="required">*</span><br />
        </p>
        <p>
          <label for="password">Password: </label>
          <input name='password' type='password' maxlength="32"/>
          <span class="required">*</span><br />
        </p>
        <p>
          <label for="repeatpassword">Confirm Password: </label>
          <input name='repeatpassword' type='password' maxlength="32"/>
          <span class="required">*</span><br />
        </p>
      </fieldset>

Link to comment
Share on other sites

Try setting your errors using:

 

/* Some if statement to check for errors in the 'name' field */ {
   $error_array['name'] = TRUE;
}

 

Then when you go to write you form:

 

<label for='name'>Name:</label><?php (($error_array['name']) ? ' <span style="color:red;">The name you entered is invalid</span>' : ''); ?>

Link to comment
Share on other sites

Just found that I can use the echo anywhere on the page before I read your post..

 

What would the

/* Some if statement to check for errors in the 'name' field */ {
   $error_array['name'] = TRUE;
}

look like if I wanted to check the name field has a min characters of 3 and max characters or 25?

 

 

Would I create a new  $error_array['name'] = TRUE; for each field?  ie. address, email, ect?

Link to comment
Share on other sites

The if would look like:

 

if (strlen($_POST['name']) < 3 || strlen($_POST['name']) > 25) {
   $error_array['name'] = TRUE;
}

 

As for the other fields, yes you would have to do the same.

 

I tend to use a custom function to gather the string lengths, a foreach loop, and a switch. If you're interested, I can post it in a bit (getting food right now).

Link to comment
Share on other sites

I tried to use the code below but the form still submitted with only 2 characters.  How would I stop it and output the error beside the form label?  Currently its just setting $error.. = TRUE.

 

 

What does your functions look like and how would I implement them into this page?

 

 

PHP Code:

<?php 
$submit = $_POST['submit'];
// Form Data
$name = strip_tags($_POST['name']);
$address = strip_tags($_POST['address']);
$email = strip_tags($_POST['email']);
$repeatemail = strip_tags($_POST['repeatemail']);
$phone = strip_tags($_POST['phone'], "Enter your Phone Number");
$salonname = strip_tags($_POST['salonname']);
$salonaddress = strip_tags($_POST['salonaddress']);
$salonprov = strip_tags($_POST['salonprov']);
$salonpostal = strip_tags($_POST['salonpostal']);
$salonconfirm = strip_tags($_POST['salonconfirm']);
$enewsletter = strip_tags($_POST['enewsletter']);
$saloncountry = strip_tags($_POST['saloncountry']);
$password = strip_tags($_POST['password']);
$repeatpassword = strip_tags($_POST['repeatpassword']);
$date = date("Y-m-d");
// Set e-mail recipient
$myemail = "info@fusionfashionhair.com";


if ($submit)
{
    //check for existance
    if ($name&&$password&&$repeatpassword&&$email)
    {
        if ($password==$repeatpassword)
        {
            if ($email==$repeatemail)
            {
                //check name length
                if (strlen($_POST['name']) < 3 || strlen($_POST['name']) > 25) {
                   $error_array['name'] = TRUE;
                 }    
                 
                 
                //check password length
                if (strlen($password)>32||strlen($password)<6)
                {
                    echo '<p class="formecho">Password must be between 6 and 32 characters</p>';
                }
                else
                {
                    // Thank you Page
                    $insertGoTo = "thankyou.php";
                    header(sprintf("Location: %s", $insertGoTo));
                    
                    // encrypt password
                    $temppass = $password;
                    $password = md5($password);
                    $repeatpassword = md5($repeatpassword);
                    
                    // dBase file
                    include "dbConfig.php";
                    //open database
                    //generate random number for activation process
                    $random = md5(rand(23456789,987654321));
                    
                    
                    // register the user!                
                    // Set default username
                    $username = $email;
    
                    // INSERT INTO user...  replace user with table name
                    // make sure you have the same number and order of values as the database has
                    $queryreg = mysql_query("
                    
                    INSERT INTO user VALUES ('','$name','$username','$password','$date','$email','$phone','$address','$salonname','$salonaddress','$salonprov','$salonpostal','$saloncountry','$salonconfirm','$enewsletter','$random','0')");
                    
                    //Insert ID based on last ID in database
                    $lastid = mysql_insert_id();
                    
                    //send activation email
                    $to = $email;
                    $subject = "Activate Salon Member Acctount at Fusion Fashion Hair";
                    $headers = "From:  webmaster@fusionfashionhair.com";
                    $server = "mail.fusionfashionhair.com";
                    
                    //change php.ini and set SMTP to $server
                    ini_set("SMTP",$server);
                    
                    
                    $body = "
                    
                    $name from $salonname is wanting a membership, \n\n
                    
                    Please click on the link provided below to activate the account with Fusion Fashion Hair
                    http://www.fusionfashionhair.com/activate.php?id=$lastid&code=$random \n\n
                    
                    Username = $username \n
                    Password = $temppass \n
                    
                    
                    Thank you,
                    
                    Customer Service
                    ";
                    
                    //function to send email
                    mail($to, $subject, $body, $headers);
                    
                }
            }    
        else
        echo '<p class="formecho">Your passwords do not match!</p>';
        }
        else
        echo '<p class="formecho">Your Emails do not match!</p>';
    }//End check Existance
    else
        echo '<p class="formecho">Please fill in <b>ALL</b> fields!</p>';
}// End if Sumbit

?>

 

Form Code:


 

Link to comment
Share on other sites

If you're formatting the input data, it's always a good idea to run your validation on the formatted data.

 

For username and password, I might do something like this:

 

function set_character_limits($type, &$min, &$max) {
   switch ($type) {
      case 'name':
         $min = 3;
         $max = 25;
         break;
      case 'password':
         $min = 6;
         $max = 32;
         break;
      default:
         $min = 0;
         $max = 0;
         break;
   }
}

$error_array = array();
$name = strip_tags($_POST['name']);
$password = strip_tags($_POST['password']);
foreach ($_POST as $key => $value) {
   $min = 0;
   $max = 0;
   set_character_limits($key, $min, $max);
   switch ($key) {
       case 'name':
       case 'password':
          if (strlen($value) < $min || strlen($value) > $max) {
             $error_array[$key] = TRUE;
          }
          break;
   }
}

if (!empty($error_array)) {
   /* Write the HTML for the form here, using my tip above to include error messages next to the erroring element */
}
else {
   /* Do stuff as though there was no error here */
}

 

The logic here is pretty straight forward if you know the syntax of a switch.

 

http://php.net/manual/en/control-structures.switch.php

Link to comment
Share on other sites

I'm very new to php and the array stuff is a little over my head at the moment.  I understand the concept/how you enter values ect but I don't know how to fit it in to this site.

 

 

So.. I'm going to stick to if statements for now, but.. I get hung up on an IF statement that should provide and error.

 

I want to only submit the form if this check box is checked on.

 

Not sure what I'm doing wrong with this if statement?

 

 

My PHP:

 

                        // Checks Proper input Salon Confirmation                        if (isset($_POST['$salonconfirm'])=='1')                        {                            echo '<p class="formecho">Please Confirm You are your Salon</p>';                        } // End checks Salon Confirm input                        else

 

 

My Form Info:

 

      <label for="salonconfirm"><span class="required">*</span></label>      <input type="checkbox" class="chkbox" name="salonconfirm" value="1">      <div class="textbox"> <font>By checking this box I confirm that I currently practice as a Hair Care Professional at the above address. I understand that Fusion Fashion Hair does not assume any responsibility for any claims that may arise from the installation of Fusion Fashion Hair's extensions</font> </div>      <!-- End Div textbox -->

 

Link to comment
Share on other sites

ok I tried using an array and set values for each array number. 

I set page echo Error above Form to:

<?php echo $current_error; ?>

 

 

Where

 

I set the $current_error based on where it stopped.

 

Web Link to Page:

http://www.fusionfashionhair.com/registration.php

 

ie.

 

$current_error=$form_error_array[0];

 

 

This doesn't seem to be working.  The Error Code on the page above the form always displays the same thing... but the echo error code at the top of the page is correct??  What the heck?

 

 

PHP Code:

 

<?php $submit = $_POST['submit'];// Form Data$name = strip_tags($_POST['name']);$address = strip_tags($_POST['address']);$email = strip_tags($_POST['email']);$repeatemail = strip_tags($_POST['repeatemail']);$phone = strip_tags($_POST['phone'], "Enter your Phone Number");$salonname = strip_tags($_POST['salonname']);$salonaddress = strip_tags($_POST['salonaddress']);$salonprov = strip_tags($_POST['salonprov']);$salonpostal = strip_tags($_POST['salonpostal']);$salonconfirm = strip_tags($_POST['salonconfirm']);$enewsletter = strip_tags($_POST['enewsletter']);$saloncountry = strip_tags($_POST['saloncountry']);$password = strip_tags($_POST['password']);$repeatpassword = strip_tags($_POST['repeatpassword']);$date = date("Y-m-d");// Set e-mail recipient$myemail = "info@fusionfashionhair.com";$form_error_array[0] = "Please Enter in ALL Fields!";$form_error_array[1] = "Please Enter Valid Name";$form_error_array[2] = "Please Enter Valid Address";$form_error_array[3] = "Please Enter Valid Email";$form_error_array[4] = "Your Email address do not match!";$form_error_array[5] = "Please Enter Valid Phone Number";$form_error_array[6] = "Password must be between 6 and 32 characters";$form_error_array[7] = "Password do not match!";$form_error_array[8] = "Please Enter Valid Salon Name";$form_error_array[9] = "Please Enter Valid Salon Address";$form_error_array[10] = "Please Select Province/State";$form_error_array[11] = "Please Enter Valid Postal/Zip Code";$form_error_array[12] = "Please Select Country";$form_error_array[13] = "Please Confirm Salon Professional ";$current_error = "No Errors";if ($submit){    // check for existance    if ($name&&$address&&$email&&$phone&&$password&&$salonname&&$salonaddress&&$salonpostal)    {        // check password input match        if ($password==$repeatpassword)        {            // checks email input match            if ($email==$repeatemail)            {                // Checks Proper input of Province/State                if ($salonprov=="Please Select" || $salonprov=="------------")                {                    echo '<p class="formecho">Please Select a Valid Province/State!</p>';                    $current_error=$form_error_array[10];                } // End checks Province/State input                else                    // Checks Proper input of Country                    if ($saloncountry=="Please Select")                    {                        echo '<p class="formecho">Please Select a Valid Country!</p>';                        $current_error=$form_error_array[12];                    } // End checks Country input                    else                                                                // Checks Proper input Salon Confirmation                        if (isset($_POST['$salonconfirm'])=='1')                        {                            echo '<p class="formecho">Please Confirm You are your Salon</p>';                            $current_error=$form_error_array[13];                        } // End checks Salon Confirm input                        else                                                                        //check password length                            if (strlen($password)>32||strlen($password)<6)                            {                                echo '<p class="formecho">Password must be between 6 and 32 characters</p>';                                $current_error=$form_error_array[6];                            } //end of password length check                                                        else                            {                                // Thank you Page                                $insertGoTo = "thankyou.php";                                header(sprintf("Location: %s", $insertGoTo));                                                                // encrypt password                                $temppass = $password;                                $password = md5($password);                                $repeatpassword = md5($repeatpassword);                                                                // dBase file                                include "dbConfig.php";                                //open database                                //generate random number for activation process                                $random = md5(rand(23456789,987654321));                                                                                                // register the user!                                                // Set default username                                $username = $email;                                                // INSERT INTO user...  replace user with table name                                // make sure you have the same number and order of values as the database has                                $queryreg = mysql_query("                                                                INSERT INTO user VALUES ('','$name','$username','$password','$date','$email','$phone','$address','$salonname','$salonaddress','$salonprov','$salonpostal','$saloncountry','$salonconfirm','$enewsletter','$random','0')");                                                                //Insert ID based on last ID in database                                $lastid = mysql_insert_id();                                                                //send activation email                                $to = $email;                                $subject = "Activate Salon Member Acctount at Fusion Fashion Hair";                                $headers = "From:  webmaster@fusionfashionhair.com";                                $server = "mail.fusionfashionhair.com";                                                                //change php.ini and set SMTP to $server                                ini_set("SMTP",$server);                                                                                                $body = "                                                                $name from $salonname is wanting a membership, \n\n                                                                Please click on the link provided below to activate the account with Fusion Fashion Hair                                http://www.fusionfashionhair.com/activate.php?id=$lastid&code=$random \n\n                                                                Username = $username \n                                Password = $temppass \n                                                                                                Thank you,                                                                Customer Service                                ";                                                                //function to send email                                mail($to, $subject, $body, $headers);                        }                            }// End of Check Emails                else                echo '<p class="formecho">Your email address do not match!</p>';                $current_error=$form_error_array[4];        }// End of Check Passwords        else            echo '<p class="formecho">Your Passwords do not match!</p>';            $current_error=$form_error_array[7];    }// End check Existance    else        echo '<p class="formecho">Please fill in <b>ALL</b> fields!</p>';        $current_error=$form_error_array[0];        }// End if Sumbit?>

 

 

From Code:

 

    <form action='registration.php' method='post' id="regform">      <fieldset>                  <legend>Personal Information</legend>        <p> </p>        <?php echo $current_error; ?>        <p> </p>        <p>          <label for='name'>Name:</label>          <!--using the value = and php echo you can store the value in the forms without re-entering the values-->          <input name='name' type='text' value='<?php echo $name; ?>' maxlength="25"/>          <span class="required">*<?php (($error_array['name']) ? ' <span style="color:red;">The name you entered is invalid</span>' : ''); ?></span><br />        </p>        <p>          <label for="address">Address: </label>          <!--using the value = and php echo you can store the value in the forms without re-entering the values-->          <input name='address' type='text' value='<?php echo $address; ?>' maxlength="25"/>          <span class="required">*</span><br />        </p>        <p>          <label for="email">Email: </label>          <!--using the value = and php echo you can store the value in the forms without re-entering the values-->          <input name='email' type='text' value='<?php echo $email; ?>' maxlength="25"/>          <span class="required">*</span><br />        </p>        <p>          <label for="repeatemail">Confirm Email:</label>          <input type='text' name='repeatemail' />          <span class="required">*</span><br />        </p>        <p>          <label for="phone">Phone: </label>          <!--using the value = and php echo you can store the value in the forms without re-entering the values-->          <input name='phone' type='text' value='<?php echo $phone; ?>' maxlength="14"/>          <span class="required">*</span><br />        </p>        <p>          <label for="password">Password: </label>          <input name='password' type='password' maxlength="32"/>          <span class="required">*</span><br />        </p>        <p>          <label for="repeatpassword">Confirm Password: </label>          <input name='repeatpassword' type='password' maxlength="32"/>          <span class="required">*</span><br />        </p>      </fieldset>

 

 

 

Link to comment
Share on other sites

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.