Tatws24
Tatws24

Reputation: 107

PHP form validation not working correctly

I am new to PHP, and doing an evening course. We have an project for a form validation. I have the following code, but when i click submit, it simply redirect to the desired site, without doing the required validation.

<?php  
$checkedMale    = $_POST['gender'] == 'Male' ? "checked='checked'" : '';
$checkedFemale  = $_POST['gender'] != 'Male' ? "checked='checked'" : '';
$formValidates = false;
if(isset($_POST['submit']) && $_POST['submit'] == 'Register') {
$errors = array();
if ( $_POST['firstName'] == '') {
    $errors[] = '<p>Please fill in your first name</p>';   
}   
if ( $_POST['surname'] == '') {     
    $errors[] = '<p>Please fill in your surname</p>';                  
}    
if ( $_POST['email'] == '') {       
    $errors[] = '<p>Please fill in your e-mail address</p>';        
       } else {     
              if ( ! filter_var ($_POST['email'],FILTER_VALIDATE_EMAIL) ) {
                      $errors[] = "<p>Please supply a valid e-mail address</p>";
                  }
               }    
if ( $_POST['address'] == '') {     
    $errors[] = '<p>Please fill in your postal address</p>';                
}  
if (count($errors)== 0) {
    $formValidates = true;
}
}
if ( ! $formValidates) {
// Displays errors 
if (count($errors) > 0 ) {
        echo "\n<ul>";
    foreach ($errors as $error){
        echo "\n\t<li>$error</li>";
    }
    echo "\n<ul>";
}
?>
<form name="questions" action="lesson8_1.php" method="post">
    <table>
        <tr>
            <th>Title:</th>
            <td>
                <select name="title">
                    <option value="">Select</option>
                    <option>Mr</option>
                    <option>Mrs</option>
                    <option>Miss</option>
                    <option>Dr</option>                    
                </select>
            </td>
        </tr>
        <tr>
            <th>First name:</th>
            <td><input type="text" name="firstName" placeholder="First Name..." value="" /></td>
        </tr>
        <tr>
            <th>Surname:</th>
            <td><input type="text" name="surname" placeholder="Surname..." value="" /></td>                                
        </tr>
        <tr>
            <th>Email:</th>
            <td><input type="text" name="email" placeholder="E-mail Address..." value="" /></td>
        </tr>
        <tr>
            <th>Address:</th>
            <td><textarea name="address" placeholder="Postal Address..."></textarea></td>
        </tr>
        <tr>
            <th>Gender:</th>
            <td>
                <input type="radio" name="gender" value="Male"      <?php echo $checkedMale?> >Male<br>
                <input type="radio" name="gender" value="Female"    <?php echo $checkedFemale?> >Female<br>
            </td>
        </tr>
        <tr>
            <th></th>
            <td>                        
                <input type='checkbox' name='option[]' value='Car' 
                <?php echo in_array('Car',  $_POST['option']) ? 'checked' : '' ?>>I have a Car licence<br>
                <input type='checkbox' name='option[]' value='Motorcycle' 
                <?php echo in_array('Motorcycle',   $_POST['option']) ? 'checked' : '' ?>>I have a Motorcycle licence<br>
                <input type='checkbox' name='option[]' value='Fishing' 
                <?php echo in_array('Fishing',  $_POST['option']) ? 'checked' : '' ?>>I have a Fishing licence<br>
                <input type='checkbox' name='option[]' value='TV' 
                <?php echo in_array('TV',   $_POST['option']) ? 'checked' : '' ?>>I have a TV licence<br>
                <input type='checkbox' name='option[]' value='Dog' 
                <?php echo in_array('Dog',  $_POST['option']) ? 'checked' : '' ?>>I have a Dog licence<br>
            </td>
        </tr>
        <tr>
            <th></th>
            <td><input type="submit" name="submit" value="Register" /></td>
        </tr>
    </table>
</form> 
<?php } else { ?>
<h1>Your form has been successfully submitted!</h1>
<?php } ?>  

Upvotes: 2

Views: 780

Answers (2)

woody180
woody180

Reputation: 41

Here is the nice way to validate your forms.

First of all - include library. After - initialize class and finally start request validation.

https://github.com/woody180/simple-php-form-validation

<?php

// Include form validation
include 'your/direction/SimplePHPValidation.php';

// Initialize class
$validation = new SimplePHPValidation();

// Validate request
$errors = $validation
            ->with($_POST['something'])
            ->rules([
                'name|Name' => 'required|alpha',
                'username|UserName' => 'required|min[4]|max[20]|alpha_num',
                'email|eMail' => 'valid_email|min[5]',
                'password|Password' => 'min[5]'
            ])
            ->validate();


Upvotes: 0

JP. Aulet
JP. Aulet

Reputation: 4418

If your php file is called: 'lesson8_1.php', the form works fine. There are a few undefinied variables, but when you submit it, it returns the desired validation (i'm testing in local).

  • Please fill in your first name

  • Please fill in your surname

  • Please fill in your e-mail address

  • Please fill in your postal address

    Title: ...

UPDATE

Your code doesn't store the values already inserted if any field is missing, you can add:

<input .... value="<?php if(isset($_POST['firstName'])){ echo $_POST['firstName']; } ?>" />

(in all your inputs) and then, if the form is submitted, but is not valid, the values are kept in the form.

UPDATE:

Save this code as: lesson8.php

<?php  

$checkedMale    = $_POST['gender'] == 'Male' ? "checked='checked'" : '';
$checkedFemale  = $_POST['gender'] != 'Male' ? "checked='checked'" : '';
$formValidates = false;

if(isset($_POST['submit']) && $_POST['submit'] == 'Register') {
    $errors = array();
    if (!isset($_POST['firstName']) || $_POST['firstName'] == '') {
        $errors[] = '<p>Please fill in your first name</p>';   
    }   
    if (!isset($_POST['surname']) ||  $_POST['surname'] == '') {     
        $errors[] = '<p>Please fill in your surname</p>';                  
    }    
    if (!isset($_POST['email']) ||  $_POST['email'] == '') {       
        $errors[] = '<p>Please fill in your e-mail address</p>';        
    } else {     
        if ( ! filter_var ($_POST['email'],FILTER_VALIDATE_EMAIL) ) {
          $errors[] = "<p>Please supply a valid e-mail address</p>";
        }
    }    
    if (!isset($_POST['address']) || $_POST['address'] == '') {     
        $errors[] = '<p>Please fill in your postal address</p>';                
    }  
    if (count($errors)== 0) {
        $formValidates = true;
    }
}

if ( ! $formValidates) {
    // Displays errors 
    if (count($errors) > 0 ) {
            echo "\n<ul>";
        foreach ($errors as $error){
            echo "\n\t<li>$error</li>";
        }
        echo "\n<ul>";
    }
?>
    <form name="questions" action="lesson8.php" method="post">
        <table>
            <tr>
                <th>Title:</th>
                <td>
                    <select name="title">
                        <option value="">Select</option>
                        <option>Mr</option>
                        <option>Mrs</option>
                        <option>Miss</option>
                        <option>Dr</option>                    
                    </select>
                </td>
            </tr>
            <tr>
                <th>First name:</th>
                <td><input type="text" name="firstName" placeholder="First Name..." value="<?php if(isset($_POST['firstName'])){ echo $_POST['firstName']; }?>" /></td>
            </tr>
            <tr>
                <th>Surname:</th>
                <td><input type="text" name="surname" placeholder="Surname..." value="<?php if(isset($_POST['surname'])){ echo $_POST['surname']; }?>" /></td>                                
            </tr>
            <tr>
                <th>Email:</th>
                <td><input type="text" name="email" placeholder="E-mail Address..." value="<?php if(isset($_POST['email'])){ echo $_POST['email']; }?>" />" /></td>
            </tr>
            <tr>
                <th>Address:</th>
                <td><textarea name="address" placeholder="Postal Address..."></textarea></td>
            </tr>
            <tr>
                <th>Gender:</th>
                <td>
                    <input type="radio" name="gender" value="Male"      <?php echo $checkedMale?> >Male<br>
                    <input type="radio" name="gender" value="Female"    <?php echo $checkedFemale?> >Female<br>
                </td>
            </tr>
            <tr>
                <th></th>
                <td>                        
                    <input type='checkbox' name='option[]' value='Car' 
                    <?php echo in_array('Car',  $_POST['option']) ? 'checked' : '' ?>>I have a Car licence<br>
                    <input type='checkbox' name='option[]' value='Motorcycle' 
                    <?php echo in_array('Motorcycle',   $_POST['option']) ? 'checked' : '' ?>>I have a Motorcycle licence<br>
                    <input type='checkbox' name='option[]' value='Fishing' 
                    <?php echo in_array('Fishing',  $_POST['option']) ? 'checked' : '' ?>>I have a Fishing licence<br>
                    <input type='checkbox' name='option[]' value='TV' 
                    <?php echo in_array('TV',   $_POST['option']) ? 'checked' : '' ?>>I have a TV licence<br>
                    <input type='checkbox' name='option[]' value='Dog' 
                    <?php echo in_array('Dog',  $_POST['option']) ? 'checked' : '' ?>>I have a Dog licence<br>
                </td>
            </tr>
            <tr>
                <th></th>
                <td><input type="submit" name="submit" value="Register" /></td>
            </tr>
        </table>
    </form> 
<?php } else { ?>
    <h1>Your form has been successfully submitted!</h1>
    <!-- here you can redirect with php to the desired location -->
<?php } ?>  

And it works as you desired i guess.

Upvotes: 1

Related Questions