Skip to content

Simple PHP Form Error Class, Validate Errors Class, OOP

Share Button
<?php 
    
/**   Simple Error Class 
*
*   - Define Error Messages, Regular Expressions 
*   - Log Errors to Error Array
*   - Sanitize Input
*   - Print/Display Errors
*
*   Please Note that this class does it's job, but you may want to do things
*   different way or change something here & there.
*   This Class gives a Patern/shows the way, of how errors could be handled in OOP way.
*   Feel free to modify,use and reffer it anyway you want.
*/

class Errors{
    
    /** Error Array for all Errors Occured during Validation/Check process */
    public $errors=array();
    
    /**
    *   All below Error Arrays will store information about Errors.
    *   i.e. 'ERROR NAME' = > 'ERROR MESSAGE'
    */
    
    /** Regular/All Error types of Errors */
    protected function validationErr(){
        $this->validate_errors = array(
            "ERR_NO_NAME"       =>   "No name provided"
        );        
        /** Return Error Array */
        return $this->validate_errors;
    }
    
    /** Regular Expression Errors */
    protected function regexErr(){
        $this->regex_errors = array(
            "ERR_REG_NAME"      => "Only(a-zA-Z) allowed. Between 1-50 Characters."
        );        
        /** Return Regex Error Array */
        return $this->regex_errors;
    }
    
    /** Regular Expressions to check input */
    protected function regexExp(){
        $this->regexExp = array(
            "REG_NAME"      => "/^[a-zA-Z]{1,50}$/"
        );
        /** Return Regular Expressions Array */
        return $this->regexExp;
    }
    
    /** Logs an Error to Regular Error Array */
    protected function logErrors($error){
        $this->errors["$error"] = $this->validationErr()["$error"];
    }
    
    /** Logs an Error to Regex Error Array */
    protected function logRegexErr($error){
        $this->errors["$error"] = $this->regexErr()["$error"];
    }
        
    /** Sanitize input */
    public function sanitizeInput($input){
        /** htmlspeciachars     Escape HTML input*/
        /** trim                Strip white spaces from beginning and end of string */
        /** strip_tags          Strip HTML & PHP tags from a string */

        strip_tags(htmlspecialchars(trim($input)));
        
        $this->sanitizedInput = $input;
        return $this->sanitizedInput;
    }
    
    /** Match Regex against value */
    protected function matchRegex($regex,$value){
        return preg_match($this->regexExp()[$regex],$value);
    }
    
    /** Check if there are any errors in Error Array */
    public function noErrors(){
        if(empty($this->errors)){
            return true;
        } else {
            return false;
        }
    }
     
    /** Below function check & display any number of arguments passed 
    *   Each argument should represent the key(Error) of FormErrors
    *   example use: printErrors("ERR_NO_NAME","ERR_REG_NAME")
    */
    public function printErrors(){  
        /**  Returns the number of arguments passed to the function */
        $numOfArgs = func_num_args();  
        /** Returns an array with all arguments passed to the function */   
        $listOfArgs = func_get_args();
        /** Loop through array & display results */
        for ($i = 0; $i < $numOfArgs; $i++) {
            if(!empty($this->errors)){
                if(array_key_exists($listOfArgs[$i],$this->errors)){
                    echo $this->errors[$listOfArgs[$i]];
                    return false;
                }
            }
        }
    }
} // Class End


/**
*   Validate Class extends Errors Class in order to utulize it's methods & functionality.
*   Below Methods specifies how arguments should be validated & let
*   specific Errors to be logged to Error Array.
*/
class Validate extends Errors {
 
    /** If name is empty echo Error */
    public function noName($name){
        if(empty($name) || is_null($name) || !$name){
            /** Log Error to the Errors Array */
            $this->logErrors("ERR_NO_NAME");
        }
    }
    
    /** Check If regular Expression matches */
    public function nameRegexName($name){        
        /** If matches REGEX return $name */
        if($this->matchRegex("REG_NAME",$name)){
             return $name;
        }else{
           /** Log Error to the Errors Array */
            $this->logRegexErr("ERR_REG_NAME");    
            return false;
        }        
    }
    
    /** Pass functions you would like to check for a $_POST['name]/$name */
    public function checkNameInput($name){
        
        /** Check for Conditions/ */
        $this->noName($name);
        $this->nameRegexName($name);   
        
        /** Check for Errors in Error Array */
        if(!$this->noErrors()){
            return false;
        }else{
            return true;
        }   
    }
} // Class End

/** Instance of a Validate Class */
$validate=new Validate();

/** Validate Submission - Check if $_POST var are set to avoid dummy errors */
if(isset($_POST['submit'])){
    if(isset($_POST['name'])){
        /** name = Sanitized name Input */
        $name=$validate->sanitizeInput($_POST['name']);
        /** Check is value has been provided */
        if($validate->checkNameInput($name)){
            header("Location: http://www.sharemyweb.com");
        } 
    }
}

?>

<h2>Valivate Whatever you want, Against whatever input You want</h2>

<!-- Input Form -->
<form action="" method="POST">
    
    <input name="name" value="" placeholder='Validate Input'> 
    <br /><br />
    <input name="submit" type="submit" value="Validate">
    
    <?php 
        /**
        *   Pass Error names to the printErrors function.
        *   Function accepts any number of Errors.
        */
    ?>
    
    <span style='color:red'>
        <?php
            $validate->printErrors("ERR_NO_NAME","ERR_REG_NAME"); 
        ?> 
    </span>
   
</form> <!-- Form End-->

 

Sample Results:

1#

Input_validate

2#

input_validate_2

3#

input_validate_3

Share Button