Web Analytics Made Easy -
StatCounter Form Error Handling - CodingForum

Announcement

Collapse
No announcement yet.

Form Error Handling

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Form Error Handling

    I completed my sign-up page, but then I thought I need to make this more efficient and more user friendly. So, I decided to redo it. What I am trying to do is check to see if the addUser form is submitted, if it is then check to see if any fields are empty. If so, then place into an errors array and output the form with the errors beside each form field and displayed at the top of the page. Then, if a field is not empty, send it through the proper validation function. If there is any errors on that part, then insert the error into the errors array and display it the same as the errors before. It looks like it is working perfectly. So, I decided to put it through some testing. If I don't fill out any of the fields it will output the form with the errors, but at the top of the screen there is the word Array at the very bottom of the displayed errors. This happens every time there is any kind of error. Then, when I complete the form, it show errors when it isn't suppose to. It shows them like this : ARRAY, [email protected], ARRAY, ARRAY. This doesn't make sense to me. Would anyone care to explain to me what is happening, and a way to fix this as well as some suggestions to make what I am doing better?

    Here is the php file:
    PHP Code:
    <?php

     
    require_once('../database_info/includes/connectvars.php');  
     require_once(
    '../database_info/includes/functions3.php');
     
    // Connect to the database 
     
    $dbc mysqli_connect(DB_HOSTDB_USERDB_PASSWORDDB_NAME);


    //$fields = array();
    //$errors = array();
    $required_fields = array('firstname''lastname''day''month''year''username''zipcode''password''password2''email');

    if (
    array_key_exists('addUser',$_POST)) {
        
    $errors checkRequiredFields($required_fields);
        
    $fields sanitizePost($required_fields);
        
    extract($fields);
        if(empty(
    $errors["zipcode"])) {
            
    $zipcodeError validateZipcode($zipcode);
            
    array_push($errors$zipcodeError);
            
    $output_form "yes";
        }
        if (empty(
    $errors["email"])) {
            
    $emailError validateEmail($email);
            
    array_push($errors$email);
            
    $output_form "yes";    
        }
        if(empty(
    $errors["username"])) {
            
    $usernameError validateUsername($username);
            
    array_push($errors$usernameError);
            
    $output_form "yes";
        }
        if(empty(
    $errors["password"]) && empty($errors["password2"])) {
            
    $passwordError validatePassword($password$password2);
            
    array_push($errors$passwordError);
            
    $output_form "yes";
        }
        if(empty(
    $errors["year"])) {
            
    $birthdayError validateBirthday($year$month$day);
            
    array_push($errors$birthdayError);
            
    $output_form "yes";
        }
        if (!empty(
    $errors)) {
            echo 
    "All form fields must be filled out.<br />";
            foreach (
    $errors as $error) {
             echo 
    $error '<br />';    
            }
            
    $output_form "yes";    
        } else {
            echo 
    "All fields are correct.<br />";
            
    $output_form "no";
        }
        
        
        
    }  else {
        
    $output_form "yes";    
    }
    if (
    $output_form == "yes") {
    ?>
    <form method="post" action="user_registration3.php">
         <label for="firstname">First Name:</label>
                <input type="text" name="firstname" id="firstname" value="<?php echo $firstname?>"/> <span><?php if(isset($errors["firstname"])) { echo $errors["firstname"];} ?></span><br /><br />
        <label for="lastname">Last Name:</label>
                <input type="text" name="lastname" id="lastname" value="<?php echo $lastname?>" /> <span><?php if(isset($errors["lastname"])) { echo $errors["lastname"];} ?></span> <br /><br />
        <label for="birthday">Birthday:</label>
                  <select title="Please choose a month" name="month" id="month"> <?php monthOptions(); ?> </select>
                <select title="Please choose a day" name="day" id="day"> <?php dayOptions(); ?> </select> 
                <select title="Please choose a year" name="year" id="year"> <?php yearOptions(20111900); ?> </select><span><?php if(isset($errors["year"])) { echo $errors["year"];} ?></span><br /> <br />
        <label for="zipcode">Zipcode:</label>
                <input type="text" name="zipcode" id="zipcode" value="<?php echo $zipcode?>" /> <span><?php if(isset($errors["zipcode"])) { echo $errors["zipcode"];} ?></span><br /><br />
        <label for="username">Username:</label>
                <input type="text" name="username" id="username" value="<?php echo $username?>"/> <span><?php if(isset($errors["username"])) { echo $errors["username"];} ?></span><br /><br />
        <label for="password">Password:</label>
                <input type="password" name="password" id="password" /> <span><?php if(isset($errors["password"])) { echo $errors["password"];} ?></span><br /><br />
        <label for="password2">Password (retype):</label>
                  <input type="password" id="password2" name="password2" /> <span><?php if(isset($errors["password2"])) { echo $errors["password2"];} ?></span><br /><br />
        <label for="email">Email:</label>
                <input type="text" name="email" id="email" value="<?php echo $email;?>" /> <span><?php if(isset($errors["email"])) { echo $errors["email"];} ?></span><br /><br />
        <input type="submit" name="addUser" value="Submit" />
    </form>
    <?php
    }
    ?>
    Here is my functions.php:
    PHP Code:
    <?php // functions3.php
    function yearOptions$endYear ''$startYear '1900' )
                {
                    for ( 
    $i $startYear$i <= $endYear$i++ )
                    {
                        ( 
    $i == date('Y') ) ? $selected ' selected="selected"' $selected '';
                        echo 
    '<option value="'.$i.'"'.$selected.'>'.$i.'</option>'."\n";
                    }
                }
                
    function 
    monthOptions()
                {
                    
    $months = array( => "January""February""March""April""May""June""July""August""September""October""November""December" );
                    
                    foreach ( 
    $months as $monthNo => $month )
                    {
                        ( 
    $monthNo == date('n') ) ? $selected ' selected="selected"' $selected '';
                        echo 
    '<option value="'.$monthNo.'"'.$selected.'>'.$month.'</option>'."\n";
                    }
                }
                
    function 
    dayOptions()
                {
                    for ( 
    $i 1$i <= 31$i++ )
                    {
                        ( 
    $i == date('j') ) ? $selected ' selected="selected"' $selected '';
                        echo 
    '<option value="'.$i.'"'.$selected.'>'.$i.'</option>'."\n";
                    }
                }
    function 
    sanitizeString($var) {
        global 
    $dbc;
        
    $var strip_tags($var);
        
    $var htmlentities($var);
        
    $var stripslashes($var);
        return 
    mysqli_real_escape_string($dbctrim($var));    
    }
    function 
    sanitizePost $required_fields ) {
       global 
    $fields;
       foreach(
    $required_fields as $fieldname) {
            
    $fields["{$fieldname}"] = sanitizeString($_POST["{$fieldname}"]);
              
        } 
      return 
    $fields;
    }

    function 
    validateZipcode($zipcode) {
        global 
    $errors;
        
    $zipcode_regex '/[0-9]{5}/';
        if (!
    preg_match($zipcode_regex$zipcode)) {
            
    $errors["zipcode"] = "Your zipcode is not valid.";
        }
       return 
    $errors;
    }

    function 
    checkRequiredFields $required_fields ) {
                    global 
    $errors;
                    foreach(
    $required_fields as $fieldname) {
                                if (!isset(
    $_POST["{$fieldname}"]) || empty($_POST["{$fieldname}"])) {
                                    
    $errors["{$fieldname}"] = ucfirst($fieldname) . " cannot be empty.";
                                 } 
                       }
                    return 
    $errors;
               }
    function 
    validateEmail($email){
        global 
    $errors;
        
    $email_regex '/^[a-zA-Z0-9][a-zA-Z0-9\._\-&!?=#]*@/';
        if(!
    preg_match($email_regex$email)) {
          
    // email is invalid because the LocalName is bad.
          
    $errors["email"] = "Your email is not valid.";
        }
        else {
            
    // strip out everything but hte domain for the email
            
    $domain preg_replace($email_regex''$email);
            
    //Now check if $domain is registered
            
    if(!checkdnsrr($domain)) {
                
    $errors["email"] = "Your email is not valid.";
            }
        }
        return 
    $errors;
    }
    function 
    validateUsername($username) {
        global 
    $errors;
        global 
    $dbc;
        
    $username_regex '/[^a-zA-Z0-9_-]/';
        if (
    strlen($username) < 6) {
            
    $errors["username"] = "Your username must be greater than 6 characters.";    
        } else if (
    preg_match($username_regex$username)) {
            
    $errors["username"] = "Your username can only consist of lowercase and uppercase letters, any numbers between 0-9, _, or - .";
        } else {
                
    $query "SELECT * FROM users WHERE username = '$username'";
                
    $result mysqli_query ($dbc$query);
                  if (
    mysqli_num_rows($result)) {
                    
    $errors["username"] = "The username you selected has already been taken. Please select another.";
                    
    $username ''
                  }
        }
        return 
    $errors;
    }
    function 
    validatePassword($password$password2) {
        global 
    $errors;
        if((
    strlen($password) < 6)) {
            
    $errors["password"] = "Your password must be longer than six character.";
        } else if (!
    preg_match('/[a-z]/'$password) || !preg_match('/[A-Z]/'$password) || !preg_match('/[0-9]/'$password)) {
            
    $errors["password"] = "Your password must have one lowercase letter, one uppercase letter, and one number between 0-9.";
        } else if (
    $password != $password2) {
            
    $errors["password"] = "Your passwords do not match.";
        }
        return 
    $errors;
    }
    function 
    validateBirthday($year$month$day) {
        global 
    $errors;
       if (!
    checkdate($month$day$year)) {
         
    $errors["year"] = "This is not a valid date. Please choose your correct birthday.";
       }
     return 
    $errors;
    }

    ?>
    Notice: If you post a problem and it gets fixed, please remember to go back and place it as solved. ;)
    I always recommend the HEAD First series of books for learning a new coding language. ^_^

  • #2
    I believe this got chucked to the second page because of all the posts. This needs a bump.
    Notice: If you post a problem and it gets fixed, please remember to go back and place it as solved. ;)
    I always recommend the HEAD First series of books for learning a new coding language. ^_^

    Comment


    • #3
      No luck anyone?
      Notice: If you post a problem and it gets fixed, please remember to go back and place it as solved. ;)
      I always recommend the HEAD First series of books for learning a new coding language. ^_^

      Comment


      • #4
        Ok, I have solved this on my own. ^_^ I'll mark it as solved. The problem was the array_push function making a multidimensional array.
        Notice: If you post a problem and it gets fixed, please remember to go back and place it as solved. ;)
        I always recommend the HEAD First series of books for learning a new coding language. ^_^

        Comment

        Working...
        X