2

I'm practicing doing simple form validation and have come unstuck trying to use a function to replace code that I repeat several times throughout the validation script.

I am trying to write a function that saves an error message to an $errors array when validation fails for that form field.

The function I'm using does not return any error messages but does not display the message that is should do when validation fails.

I'm testing it on just one filed, the username field and with just one validation rule, username cannot be blank.

NB/ The form and validation worked when I was not trying to use a function.

Here is what I have, what a I doing wrong? I'm struggling to get to grips with functions :-(

functions.php

<?php
//Function to deal with saving error messages to errors array
// @param - 2 parameters. Name of field that has the error; Error message string
// @return - an error message string

function errorHandler($errField, $errMsg){

    $errors[$errField] = $errMsg;

return $errors;

}

index.php

<?php
include_once '_includes/headers.php';
include_once '_includes/functions.php';
?>

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

//Initialize variables
$data = array();//Store cleaned valid data for output
$errors = array();//Store error messages
$form_is_submitted = false;
$errors_detected = false;

if(isset($_POST['registerBtn'])){

    $form_is_submitted = true;

    //VALIDATE FORM

    //Validate - Username
    if (isset($_POST['username'])) {

        $username = trim($_POST['username']);

        //Username cannot be blank - validation
        if($username !== ''){

            $data['username'] = htmlentities($username);

            //Get the length of the string
            $stringLength = strlen($username);

            //Username minimum 5 maximum 15 characters long - validation
            if($stringLength < 5 || $stringLength > 15){

                $errors_detected = true;

                $errors['username'] = ' Invalid length. Must be between 5 - 15 characters!';

            }else {

                $data['username'] = htmlentities($username);
            }

            //Username must only be alphanumeric characters - validation
            if(!ctype_alnum($username)){

                $errors_detected = true;

                $errors['username'] = ' Invalid characters. Alphanumeric characters only!';
            }else {

                $data['username'] = htmlentities($username);
            }


        }else {

            $errors_detected = true;

            //Call error message function
            if($errors_detected === true){

                errorHandler('username', ' Field cannot be blank!');

            }

        }

    }else {

        $errors_detected = true;

        $errors['username'] = ' Is not set!';

    }



    //Validate - Email
    if(isset($_POST['email'])){

        $email = trim($_POST['email']);

        //Email cannot be blank - validation
        if($email !== ''){

            $data['email'] = htmlentities($email);

            //Email must be valid format - validation
            if(!filter_var($email, FILTER_VALIDATE_EMAIL)){

                $errors_detected = true;

                $errors['email'] = ' Invalid email format!';

            }else {

                $data['email'] = htmlentities($email);
            }


        }else{

            $errors_detected = true;

            $errors['email'] = ' Email address is required!';
        }
    }else {

        $errors_detected = true;

        $errors['email'] = " is not set!";
    }

}

//Declare form output variable
$output = '';

//IF VALID SUBMISSION
if($form_is_submitted === true && $errors_detected === false){

    $output .= '<h3>Form successfully submitted</h3>';

    echo $output;

    foreach($data as $keys => $values){

        echo "<p>$keys : $values</p>";

    }

} else {

    //IF INVALID SUBMISSION


        if($errors_detected === true){

            $output .= '<h2>There are errors on the form</h2>';

            echo $output;

            foreach($errors as $key => $value){

                echo "<p>" . htmlentities($key) . ':' . htmlentities($value) . "</p>";
            }


        }



        //DISPLAY/REDISPLAY FORM

        $self = htmlentities($_SERVER['PHP_SELF']);

        $output ='

        <form action="'. $self .'" method="post">
    <fieldset id="registration">
        <legend>Register</legend>

        <p>Insert your profile information:</p>

            <div>
                <label for="username">Username</label>
                <input id="username" name="username" type=text value="' . (isset($data['username']) ? $data['username'] : '') . '" />
            </div>

            <div>
                <label for="email">Email</label>
                <input id="email" name="email" type=email value="' . (isset($data['email']) ? $data['email'] : '') . '" />
            </div>

            <input type="submit" id="registerBtn" name="registerBtn" value="Register" />

    </fieldset>


</form>

    ';

        echo $output;


}


?>



<?php
include_once '_includes/footers.php';
?>

UPDATE: I have updated my function to use the $errors array in my function. This should now no longer be a scope issue I think. As per Francesco Malatesta below ...

  • 2
    It looks like the `$errors` variable will be out of scope in your function. You'll need to pass that variable to your function or define it as a global. See [variable scope @ php.net](http://php.net/manual/en/language.variables.scope.php) and [What is variable scope](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) and possibly [this post](http://stackoverflow.com/questions/15165427/why-php-variable-scope-not-working-in-function) – showdev Sep 08 '15 at 17:30

2 Answers2

2

First of all, you should study something about objects, classes, exceptions and more complex stuff for this kind of job. I am assuming you want to learn about functions and do some practice.

You should, first of all, pass the errors array as a parameter.

Like this:

function errorHandler($errorsArray, $errField, $errMsg){

    $errorsArray[$errField] = $errMsg;

   return $errorsArray;

}

And then, in your index.php file:

errorHandler($errors, 'username', ' Field cannot be blank!');

This should work, because you must use the $errors array in your function. It's a scope-related problem.

However, after this, forget everything (well, not everything) and study OOP and Exceptions :)

  • Hi, I've seen exceptions in a few online tutorials but I don't think I'm at that level of understanding yet. So I have made the changes you suggest but no difference. Still it appears that the $errors['username'] is not being updated when validation fails. – Maurice Greenland Sep 08 '15 at 19:26
  • 1
    Wait, are you assigning to _$errors_ the value of _errorHandler('username', ' Field cannot be blank!');_? :) Do this: _$errors = errorHandler('username', ' Field cannot be blank!');_ – Francesco Malatesta Sep 08 '15 at 19:32
  • Yes perfect thanks that works! So, I must assign the returned value of the function to the array $errors. Eg: $errors = errorHandler($errors, 'username', ' Field cannot be blank!'); – Maurice Greenland Sep 08 '15 at 19:39
0

Have you heard about Exceptions?

Simple example to use a exception:

<?php

 try {
 // your if's
 if(40 > 30) {
   throw new Exception("40 is a bigger");
 }
} catch (Exception $error) {
   echo 'Your error is: '.$error->getMessage();
}

?>
UnderPhp
  • 328
  • 1
  • 2
  • 14