PHP Classes

Easy Validation: Validate array of submitted form values

Recommend this page to a friend!
  Info   View files Example   Screenshots Screenshots   View files View files (4)   DownloadInstall with Composer Download .zip   Reputation   Support forum (1)   Blog    
Ratings Unique User Downloads Download Rankings
StarStarStar 56%Total: 244 All time: 7,991 This week: 455Up
Version License PHP version Categories
easy-validation 1.0GNU General Publi...5PHP 5, Validation
Description 

Author

This class can validate array of submitted form values.

It takes an array with definition of rules to validate given submitted form values.

The class sets an array of error messages for the values that to not satisfy the specified rules.

Currently it can validate values for required entries, numbers, alphanumeric text, email addresses, regular expressions, minumum and maximum text length.

Picture of meivin123
  Performance   Level  
Name: meivin123 <contact>
Classes: 2 packages by
Country: Germany Germany
Age: ???
All time rank: 3659203 in Germany Germany
Week rank: 321 Up11 in Germany Germany Up
Innovation award
Innovation award
Nominee: 1x

Example

<?php
require_once("EasyValidation.php");
$rules = array(
   
"username" => array("required"=>true, "minLength"=>5, "maxLength"=>30, "pcre"=>"/^[a-zA-Z]*$/"),
   
"password" => array("required"=>true, "minLength"=>5, "maxLength"=>100),
   
"email" => array("email"=>true)
);
$errMsgs = array(
   
"#password" => array("minLength"=>"For security plase make sure your pass is minimum :value chars long."),
   
"pcre" => "Not matches pattern.",
   
"required" => ":field is required.",
   
"alnum"=> ":field should only contain alphanumeric characters.",
   
"minLength" => ":field must be a minimum of :value characters.",
   
"maxLength" => ":field must be a maximum of :value characters.",
   
"email" => "Not a valid email address."
);
try{
if( !empty(
$_POST["submit"]) ){
   
   
$validator = new EasyValidation($errMsgs);
   
$validator->check($_POST, $rules);
  
    if(
$e = $validator->getErrors() ){
        echo
"<pre>", print_r($e), "</pre>";
    }
    else{
        echo
"<b>Valid</b>";
    }
}
}
catch(
Exception $e){
    echo
$e->getMessage();
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            ul{
                list-style: none;
            }
            li{
                margin: 5px 0;
                font-size: 1.2em;
            }
            label{
                display: inline-block;
                width: 200px;
            }
        </style>
    </head>
    <body>
        <form action="" method="POST">
            <ul>
                <li>
                    <label for="username">Username</label>
                    <input type="text" name="username" id="username" />
                </li>
                <li>
                    <label for="email">Email</label>
                    <input type="email" name="email" id="email" />
                </li>
                <li>
                    <label for="password">Password</label>
                    <input type="password" name="password" id="password" />
                </li>
                <li>
                   <input type="submit" name="submit" value="Register" />
                </li>
            </ul>
        </form>
    </body>
</html>


Details

EasyValidation Manual: Author: Marvin Petker Version: 1.0 Date: 2014-09-23 License: GNU General Public License 3.0 License URL: http://www.gnu.org/licenses/gpl-3.0.txt Description: This class is used for easy validation of input data. Note: The Idea for that class came from phpacademy.org and their youtube channel. I've changed some things but I recommend you to watch their tutorials because they're very good and can give beginners an understanding of oop and other stuff. Table of Contents: 0. Introduction and requirements Line 13 1. Defining rules Line 23 2. Defining error messages Line 50 3. Validating Line 88 4. Extending the class Line 116 5. Available rules Line 150 ------------------------------------------------------------------- 0. Introduction and requirements Hello World, I wrote this class to create an easy, extendable solution for validating user input. As I wrote in the class comment I got inspired by www.phpacademy.org and I wanna thank them. To the class, I wrote it in PHP 5.5.3 but will test earlier versions soon. To use the class simply add the class via require or an autoloader to your script. DONT FORGET to wrap all actions of the EasyValidation class inside a try-catch-block. ------------------------------------------------------------------- 1. Defining rules First before we start we have to define our rules to check. Every rule has its own method and the class wil throw an exception if there is no equivalent message. All rules can be seen in 6. Possible rules. We define our rules with an associative array, where our keys are the field the rules are applied to and the rules themselfs are wrapped in another array with the rule as key=>value pairs. !!!NOTE!!! If rules for a field aren't defined the field will be ignored and not checked. Example: <?php //After sending a form the $_POST can look like this: $_POST = array("username"=>"test123", "password"=>"mysecretpass123", "email"=>"test@mail.de", "submit"=>"register"); //We now have an username, a password and an email field ind our post. //Every rule key must apply to a key from the array to check. $rules = array( "username" => array("required"=>true, "minLength"=>5, "maxLength"=>20, "alnum"=>true), "password" => array("required"=>true, "minLength"=>5, "maxLenght"=>40), "email" => array("email"=>true) ) ?> ------------------------------------------------------------------- 2. Defining error messages We have the possibility to set our custom error messages and this is also required. We have to set an error message for ever rule we are checking for. For the above example we need messages for required, minLength, maxLength, alnum, email. We define messages in a similar way like the rules. Now we use key=>value pairs in rule=>message format. <?php $errMsgs = array( "required" => "The :field is required.", "minLength" => "The :field must be of minimum :value chars.", "maxLength" => "The :field and must be of maximum :value chars.", "alnum" => "The :field should only contain alphanmerical chars.", "email" => "No valid email entered." ) ?> We the ability to use :field, :value placeholder. These are gonna be replaced with the field name (exmp. username) and the value is the satisfier of the rule so for required it would be true (thats why you shouldnt do that) and in minLength for the username it would be 5. You can also set rulesets for a specific field/key like the following: <?php //Format: "#fieldname" => array("rule"=>"message"); //Special messages for username: $errMsgs = array( "required" => "The :field is required.", "minLength" => "The :field must be of minimum :value chars.", "#username" => array("required"=>"Please enter an username", "anotherrule"=>"message") ) ?> Rules for a specific field will override regular rules. If a message for a rule is missing in a specific ruleset the class will take the regular rule ------------------------------------------------------------------- 3. Validating and error handling Now our rules and messages are defined we can validate like the following: <?php //Rules defined //Messages defined $validator = new EasyValidation($errMsgs); $validator->check($_POST, $rules); if( $e = $validator->getErrors() ){ //Errors occured } else{ //No errors occured } ?> Get Errors returns an associative array in the following format: array( "fieldname" => array( "rule1" => "message", "rule2" => "message" ... ) ) ------------------------------------------------------------------- 4. Extending the class To add your own rules you can easily extend the class and add your own methods. Every method that is added must accept at least one and maximum two parameters. If we want to add the rule "url" our satisfier would be true and we would implement it like the following: <?php class MyValidator extends EasyValidation{ //URL validation protected function url($value){ return filter_var($value, FILTER_VALIDATE_URL); } //IP validation, rule would be for exmpl. "ip"=>"ipv6" protected function ip($value, $type){ switch($type){ case "ipv4": return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); break; case "ipv6": return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6); break; } } //More of your custom rules } ?> ------------------------------------------------------------------- 5. Available rules: required => true email => true alnum => true digit => true alpha => true bool => true int => true numeric => true string => true float => true minLength => value maxLength => value pcre => pattern

Screenshots  
  • usage_screen.jpg
  Files folder image Files  
File Role Description
Plain text file EasyValidation.php Class Main class
Plain text file index.php Example Demo
Plain text file README_LONG.php Doc. Long Description and usage tutorial
Plain text file README_SHORT.php Doc. Short Description

 Version Control Unique User Downloads Download Rankings  
 0%
Total:244
This week:0
All time:7,991
This week:455Up
User Ratings User Comments (1)
 All time
Utility:68%StarStarStarStar
Consistency:68%StarStarStarStar
Documentation:75%StarStarStarStar
Examples:75%StarStarStarStar
Tests:-
Videos:-
Overall:56%StarStarStar
Rank:1831
 
Thats a good class ;-)
9 years ago (José Filipe Lopes Santos)
80%StarStarStarStarStar