0

I am performing a Form Validation in PHP. My purpose is to show the error message at the same page with form, in order to be clear for the user.

But I have to problems. First how to hide my form, where are no errors in submitting it(I want to print onl one message in this case and to hide the frm). I am trying to use:

if(false === $error)
        {
            //Validimi perfundoi me sukses!

            echo "<script> 
                document.getElementById('wrap').style.display = 'none';
        </script>";

         echo $name;
        } 

but it does not function.

Second I am having problems with checkbox validation. I am using the array $activity, to save values from checkbox, as they may be multiple values, but when the user select no value at all at the checkbox part, it gives me the error that: Warning: in_array() expects parameter 2 to be array, null given even i have initialized $activity as an arra: $activity=array();.

<?php
$name_error='';
$device_error ='';
$OS_error='';
$activity_error='';
$device='';
$OS='';
$activity=array();
if(!empty($_POST['submitted']))
{//nese form eshte submitted atehere validohen fushat
    $name = trim($_POST['name']);//heq hapesirat
    $error = false;

    if(empty($name))
    {
        $name_error='Emri eshte bosh. Ju lutem plotesoni emrin.';
        $error=true;
    }

    if(empty($_POST['device']))
    {
        $device_error = "Ju lutem selektoni nje pajisje";
        $error=true;
    }
    else
    {
        $device = $_POST['device'];
    }

    if(empty($_POST['OS']))
    {
        $OS_error ="Ju lutem selektoni sistemin operativ";
        $error=true;
    }
    else
    {
        $OS = $_POST['OS'];
    }

    if(empty($_POST['activity']) || count($_POST['activity']) < 2)
    {
        $activity_error = "Ju lutem selektoni te pakten 2 aktivitete";
        $error=true;
    }

    $activity = $_POST['activity'];

    if(false === $error)
    {
        //Validimi perfundoi me sukses!

        echo "<script> 
            document.getElementById('wrap').style.display = 'none';
    </script>";

     echo $name;
    }
}
?>
<!DOCTYPE html>
<html >
<head>
    <title>Computer Form</title>
    <link href="compForm.css" rel="stylesheet" type="text/css" />
</head>
<body >
    <div id="wrap" style="display: block">
        <form method="post" action='?' id="compform" >
        <div>
            <div class="cont_order">
               <fieldset>
               <legend>Beni zgjedhjen tuaj!</legend>
                <div class='field_container'>
                <label >Zgjidhni pajisjen qe perdorni me shpesh:</label>
                <span class="error"><?php echo $device_error;?></span>
                <label class='radiolabel'><input type="radio"  name="device" value="Desktop"  
                <?php echo ($device=='Desktop')? 'checked':''; ?>/>Desktop</label><br/>
                <label class='radiolabel'><input type="radio"  name="device" value="Laptop" 
                <?php echo ($device=='Laptop')? 'checked':''; ?> />Laptop</label><br/>
                <label class='radiolabel'><input type="radio"  name="device" value="Tablet" 
                <?php echo ($device=='Tablet')? 'checked':''; ?> />Tablet</label><br/>
                </div>


                <div class='field_container'>
                    <label for="OS">Zgjidhni Sistemin e Operimit qe perdorni:</label >
                    <span class='error'><?php echo $OS_error?></span>
                    <select id="OS" name='OS' >
                    <option value="">Zgjidhni OS</option>
                    <option <?php echo $OS=='Windows'?'selected':''; ?> >Windows</option>
                    <option <?php echo $OS=='Linux'?'selected':''; ?> >Linux</option>
                    <option <?php echo $OS=='Mac'?'selected':''; ?> >Mac</option>
                   </select>
                </div>

                <div class='field_container'>
                    <label >Selektoni dy aktivitetet qe preferoni me shume:</label>
                    <span class='error'><?php echo $activity_error ?></span>
                    <label><input type="checkbox" value="Programim Desktop" name='activity[]'
                    <?php echo (in_array('Programim Desktop',$activity)) ?'checked':'' ?>  />Programim Desktop</label>
                    <label><input type="checkbox" value="Programim Web" name='activity[]' 
                    <?php echo (in_array('Programim Web',$activity)) ?'checked':'' ?> />Programim Web</label>
                    <label><input type="checkbox" value="Dizenjim" name='activity[]' 
                    <?php echo (in_array('Dizenjim',$activity)) ?'checked':'' ?> />Dizenjim</label>
                    <label><input type="checkbox" value="Analize te dhenash" name='activity[]' 
                    <?php echo (in_array('Analize te dhenash',$activity)) ?'checked':'' ?> />Analize te dhenash</label>
                    <label><input type="checkbox" value="Kerkim shkencor" name='activity[]' 
                    <?php echo (in_array('Kerkim shkencor',$activity))?> />Kerkim shkencor</label>
               </div>

              </fieldset>
            </div>


            <div class="cont_details">
                <fieldset>
                <legend>Detajet e kontaktit</legend>
                <label for='name'>Emri</label>
                <input type="text" id="name" name='name' 
                value='<?php echo htmlentities($name) ?>' />
                <span class='error'><?php echo $name_error ?></span>
                <br/>
                <label for='address'>Adresa e emailit</label>
                <input type="email" id="address" name='address' />
                <br/>
                </fieldset>
            </div>

         <input type='submit' name='submitted' id='submit' value='Submit'  />
        </div>  
       </form>
    </div>

</body>
</html>
orsina
  • 131
  • 11
  • What do you see if you echo `$error`? – Steve Jan 24 '16 at 05:29
  • How to check if checkbox array is set http://stackoverflow.com/questions/4554758/how-to-read-if-a-checkbox-is-checked-in-php the accepted answer and rybo111's answer Remember to use `htmlspecialchars()` on any user input you will echo to prevent script attack. – Steve Jan 24 '16 at 06:06
  • The errors are coming from `echo (in_array('Programim Web',$activity)) ?'checked':''` etc, where you need to add the `isset()` to those too, so you don't do the `in_array()` on it if it is empty. – Steve Jan 24 '16 at 06:52
  • Thanks @Steve. I use . It function now – orsina Jan 24 '16 at 15:45
  • Another way to approach using the value is to have your expected responses in an array and only have numerical values in your HTML in dropdowns or checkboxes/radio buttons. Then you only need to use `intval($_POST['your_submitted_number']);` which effectively sanitises it by forcing integer value (anything else will come out as 0). http://stackoverflow.com/questions/34812089/selecting-default-value-in-html-dropdown-list/34817939#34817939 and http://stackoverflow.com/questions/34361452/many-elements-of-a-listbox-to-another/34367418#34367418 as examples. Glad that worked for you. – Steve Jan 24 '16 at 17:36

2 Answers2

0

Here's my quick solution (untested). Let's clean up your code a little:

  • Instead of using (and wasting) separate variables for each error message, let's use an associative array called $errors. The keys will be the name of the inputs and the values will be their respective error messages.

  • To ensure that you don't get warnings from undeclared variables, we will declare variables for each input at the top of the page.

  • Let's also use a new variable $submitted to know whether the form was submitted or not.

Now, if the form was $submitted and there are no (!) $errors, then we hide the form. Otherwise, we show the form and any errors if there are any.

<?php
$name = '';
$device = '';
$OS = '';
$activity = array();
$submitted = !empty($_POST['submitted']);
$errors = array();

if ($submitted) {
    //nese form eshte submitted atehere validohen fushat
    if (empty($_POST['name'])) {
        $errors['name'] ='Emri eshte bosh. Ju lutem plotesoni emrin.';
    } else {
        $name = trim($_POST['name']);
    }
    if (empty($_POST['device'])) {
        $errors['device'] = "Ju lutem selektoni nje pajisje";
    } else{
        $device = $_POST['device'];
    }
    if (empty($_POST['OS'])) {
        $errors['OS'] = "Ju lutem selektoni sistemin operativ";
    } else {
        $OS = $_POST['OS'];
    }
    if (empty($_POST['activity']) || count($_POST['activity']) < 2) {
        $errors['activity'] = "Ju lutem selektoni te pakten 2 aktivitete";
    } else {
        $activity = $_POST['activity'];
    }
}
?>
<!DOCTYPE html>
<html >
<head>
    <title>Computer Form</title>
    <link href="compForm.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php if ($submitted && !$errors) : ?>
    <?php echo $name ?>
<?php else : ?>
    <div id="wrap">
        <form method="post" action='?' id="compform" >
        <div>
            <div class="cont_order">
               <fieldset>
               <legend>Beni zgjedhjen tuaj!</legend>
                <div class='field_container'>
                    <label >Zgjidhni pajisjen qe perdorni me shpesh:</label>
                    <span class="error"><?php echo isset($errors['device']) ? $errors['device'] : '' ?></span>
                    <label class='radiolabel'><input type="radio" name="device" value="Desktop"  
                    <?php echo $device == 'Desktop' ? 'checked' : '' ?>/>Desktop</label><br/>
                    <label class='radiolabel'><input type="radio" name="device" value="Laptop" 
                    <?php echo $device == 'Laptop' ? 'checked' : '' ?> />Laptop</label><br/>
                    <label class='radiolabel'><input type="radio" name="device" value="Tablet" 
                    <?php echo $device == 'Tablet' ? 'checked' : '' ?> />Tablet</label><br/>
                </div>


                <div class='field_container'>
                    <label for="OS">Zgjidhni Sistemin e Operimit qe perdorni:</label >
                    <span class='error'><?php echo isset($errors['OS']) ? $errors['OS'] : '' ?></span>
                    <select id="OS" name='OS' >
                        <option value="">Zgjidhni OS</option>
                        <option <?php echo $OS == 'Windows' ? 'selected' : '' ?> >Windows</option>
                        <option <?php echo $OS == 'Linux' ? 'selected' : '' ?> >Linux</option>
                        <option <?php echo $OS == 'Mac' ? 'selected' : '' ?> >Mac</option>
                    </select>
                </div>

                <div class='field_container'>
                    <label >Selektoni dy aktivitetet qe preferoni me shume:</label>
                    <span class='error'><?php echo isset($errors['activity']) ? $errors['activity'] : '' ?></span>
                    <label><input type="checkbox" value="Programim Desktop" name='activity[]'
                    <?php echo in_array('Programim Desktop', $activity) ? 'checked' : '' ?>  />Programim Desktop</label>
                    <label><input type="checkbox" value="Programim Web" name='activity[]' 
                    <?php echo in_array('Programim Web', $activity) ? 'checked' : '' ?> />Programim Web</label>
                    <label><input type="checkbox" value="Dizenjim" name='activity[]' 
                    <?php echo in_array('Dizenjim', $activity) ? 'checked' : '' ?> />Dizenjim</label>
                    <label><input type="checkbox" value="Analize te dhenash" name='activity[]' 
                    <?php echo in_array('Analize te dhenash', $activity) ? 'checked' : '' ?> />Analize te dhenash</label>
                    <label><input type="checkbox" value="Kerkim shkencor" name='activity[]' 
                    <?php echo in_array('Kerkim shkencor', $activity) ? 'checked' : '' ?> />Kerkim shkencor</label>
               </div>

              </fieldset>
            </div>


            <div class="cont_details">
                <fieldset>
                    <legend>Detajet e kontaktit</legend>
                    <label for='name'>Emri</label>
                    <input type="text" id="name" name='name' value='<?php echo htmlentities($name) ?>' />
                    <span class='error'><?php echo isset($errors['name']) ? $errors['name'] : '' ?></span>
                    <br/>
                    <label for='address'>Adresa e emailit</label>
                    <input type="email" id="address" name='address' />
                    <br/>
                </fieldset>
            </div>

         <input type='submit' name='submitted' id='submit' value='Submit'  />
        </div>  
       </form>
    </div>
<?php endif ?>
</body>
</html>
Mikey
  • 6,728
  • 4
  • 22
  • 45
0

You can check the $_POST['submitted'] as below pseudocode:

//form is submitted
if isset $_POST['submitted']
    //process form and show error message
else
    //show form
Aris
  • 4,643
  • 1
  • 41
  • 38