2

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 } ?>  
2
  • The <form> open tag is missing. Commented Mar 15, 2016 at 20:12
  • look up some other examples of how to submit a php form after validation stackoverflow.com/questions/3206166/… Commented Mar 15, 2016 at 20:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, the file is called lesson8_1.php. However, if i click submit with the form empty, it still redirects to the page, without validating anything. Any idea why?
I copy paste your code and executed as is in my computer and it works fine. I added a line error_reporting(0); at beggining to not see the warnings, but when i submit the form, it redirects to the same page and outputs the validation errors correctly. Can you explain more the situation? The page redirects well i guess.
If i leave the first name field blank, i want the form to stay on lesson8.php, and display the error message - i.e. Please enter your first name. When i click submit with the fields blank/empty, it still redirects to lesson8_1.php, with only some fields complete/filled in.
Ok. Your file must be named 'lesson8.php' and the form action should be: 'lesson8.php'. Then, when submitted, the form will call the same file and do the validation. If everything is all right, you can then redirect to 'lesson8_1.php' with header('Location: ...');. Is not the best way to validate forms, but it should work.
Basically, not sure if i've explained myself clearly. Essentially, lesson8_1.php is just a page which just echo's the form results. Is header('Location: ...'); okay to do that? And where would i add that code?
|
0

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();


1 Comment

Hello, your answer does not directly answer OP's question: helping solve his code issue, as he may need to do it from scratch for his courses. But you could add it as a comment, about other/better ways to "generally handle PHP form validation"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.