php form validation error messages

Hello Experts,

Do not get me wrong that's not how i validate my forms :-) but... i know how to echo an error message per form field. Yet i am trying to understand how this is possible to do this using the "foreach" loop and then echo an error message per field in case it is empty. Thank you so much!

<?php

   $contactName = htmlentities(trim($_POST["contactName"]));
   $contactPhone = htmlentities(trim($_POST["contactPhone"]));

   $requiredFields = array('$contactName', '$contactPhone');
   
   foreach ($requiredFields as $requiredField) {
      
     if ($requiredField === '') {

    ///////// if the $contactName is left empty then
    
     $err_contactName = "please enter your name";

   //////// if the $contactPhone is left empty then

     $err_contactPhone = "please enter your phone";
    }
?>

Open in new window

RefaelAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ArgentiCommented:
if (empty($yourVariable)) {
   // your code goes here
}

Open in new window


http://www.php.net/manual/en/function.empty.php
0
Ray PaseurCommented:
There is a little more to it than that.  This example could be upgraded to use jQuery validation, and that would probably add to a better client experience.  But for just the PHP example, this shows the moving parts.

Please see http://www.laprbass.com/RAY_form_highlight_errors.php

<?php // RAY_form_highlight_errors.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT
// CLIENT IS ASKED TO PUT IN A VALUE
// IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
// WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
// WE TURN THE FORM BORDER RED
// SEE http://www.w3schools.com/CSS/pr_class_visibility.asp


// THESE CONDITIONS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = 'hidden';
$boxer_abc = 'black';
$error_xyz = 'hidden';
$boxer_xyz = 'black';
$error_any = 'hidden';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $boxer_abc = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $boxer_xyz = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OOPS - WE HAVE ERRORS AND MUST SHOW THE FORM AGAIN
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

HTH, ~Ray
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RefaelAuthor Commented:
Hi Argenti,

I think you missed the questions.... please read again :-) Thank you anyway.
0
Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

RefaelAuthor Commented:
Hello Ray_Paseur, The expert :-)

Well, I already have a client-side (javascript) validation. I simply wanted to know how to work with the loop on the required fields and setting the correct message per field.
I am sure your solution is 10 times better :-) I will have to find the time to learn/go through it. Thank you!
0
Ray PaseurCommented:
See if this makes sense...  Dealing with external input in PHP is a large topic unto itself!
http://php.net/manual/en/tutorial.forms.php
http://php.net/manual/en/language.variables.external.php
http://php.net/manual/en/security.intro.php

This is untested code; please use it as "advice" and not as an example of something that is suitable for your application work.

<?php // RAY_temp_refael.php
error_reporting(E_ALL);

// THE REQUIRED FIELDS ARE ARRAY KEYS IN THE POST REQUEST
$requiredFields = array('contactName', 'contactPhone');

// THE ERROR MESSAGES, IF ANY, WILL GO HERE
$err = array();

// USING OUR INTERNAL VARIABLES, CHECK THE POST ARRAY
foreach ($requiredFields as $key)
{
    if (empty($_POST[$key]))
    {
        $err[] = "Please Enter $key";
    }
    else
    {
        // IMPORTANT! SANITIZE THE EXTERNAL INPUT HERE (DO NOT JUST COPY IT!)
        $safe_post[$key] = $_POST[$key];
    }
}

// IF THERE ARE ANY OMISSIONS OR ERRORS, SHOW THE ERROR MESSAGES
if (!empty($err))
{
    foreach ($err as $msg)
    {
        echo PHP_EOL . $msg;
    }
    die('FAILURE');
}

// IF WE GET HERE, WE HAVE FOUND ALL OF THE FIELDS TO BE FILLED IN
// AND NOW WE CAN USE THE SANITIZED INFORMATION IN $safe_post
print_r($safe_post);

Open in new window

0
RefaelAuthor Commented:
Hi Ray_Paseur,

The above links and the example you wrote are a great lesson and i am sure many here in EE will enjoy it and will be thank you for it. I thank you too, again!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.