In a few examples, the basic usage of HRC class is introduced. The idea of development of this class was to create a library which is easy to learn, easy to set up, easy to use. HRC supports chanability to write less ;)
//Create object to check $_POST array $hrc = new HRC("POST"); //the constructor only accepts a name (as string) of a superglobal //Or instead, you can use the method HRC::setVarToCheck( $array ) $hrc->setVarToCheck($_POST); //or you can validate just any array $hrc->setVarToCheck($aMyArray);
We have created an object and specified which variable to work with.
Now, we need to specify what attributes to check and what validation rules to use. Rules are basically functions (callables) that are called in order to validate some value. For some cases, such as validating integer values or e-mails, you can use one of the HRC constants which provides an easier access to the function filer_var.
//check integer param $_POST["age"] that can't be a negative number (>=0) $hrc->check("age")->addRule( HRC::INT, 0, 200 ); // 0 is minimal value, 200 maximal //you can check nested parameters, e.g.$_POST["mother"]["age"] $hrc // you must specify a key used to access the value from $hrc object ->check(array("mother", "age"), "mothersAge" ) ->addRule( HRC::INT, 0 ); //you don't have to write all the rules again, if you just want to reuse them //HRC::checkAlso() copies the rules from the last checked parameter $hrc->checkAlso(array("father", "age"), "fathersAge" ); //The rules can be created providing HRC const. or you can use any callable //To check that a passed param. is a single character, you can do $hrc->check("singleChar")->addRule( "strlen", array(), NULL, "==", 1); //That means strlen("..your parameter..") == 1 //It can be simplified to (because of default values) $hrc->check("singleChar")->addRule( "strlen", "==", 1); //this checks for a non-empty string - similar to if( strlen(...) ) ... $hrc->check("string")->addRule( "strlen" );
Using an HRC constant is just a shortcut to use more complex validation functions. Currently, it is used just for the function filter_var(). In the code below, you can see two equivalents of the same rule:
//a rule to confirm we work with an integer value in a range $min..$max $hrc->addRule( HRC::INT , $min, $max); //is equivalant to $hrc->addRule( "filter_var", array(FILTER_VALIDATE_INT, array("min_range"=>$min, "max_range"=>$max)), 0, "!==", null );
These were the basics how to specify rules to validate (usually) a string representing e.g. an integer. If you want to validate an array of integers (or any other type of values), the process of setting rules is pretty much the same.
//you can also check an array of items, e.g. integers $hrc->check("positiveNums")->addArrayItemRule( HRC::INT, 0 ); //or the shorter version $hrc->check("positiveNums")->addAIRule( HRC::INT, 0 ); //That means $_POST["positiveNums"] has to be an array where each item is int //addAIRule sets a rule for every single item of the array. You can also validate //the array itself $hrc->check("positiveNums")->addRule( "count", "==", 10 ); //now, the array $_POST["positiveNums"] needs to have exactly 10 elements
You validate and obtain values in the same step. If anything fails, a HRCException will be thrown, so you should wrap it in try and catch block.
//try block for validation & obtaining values try{ //Now, we can retrieve the values; the validation rules are applied here $letter = $hrc->get("singleChar"); $age = $hrc->get("age"); //or get the mother's age using the specified name $momsAge = $hrc->get("mothersAge"); //or you simply get everything that you specified in a single array $data = $hrc->getAll(); }catch(HRCException $e){ //error occured, handle the exception.. $aInfo = $e->getInfo(); /* [RULE] => Array ( [fn] => strlen [args] => Array ( ) [argIndex] => [cmpOp] => == [cmpVal] => 1 [checkArrayItems] => 0 ) [VALUE] => hello world [KEY] => [singleChar] [SETTING] => singleChar [DEPTH] => 0 */ }
By default, all the checked parameters are required. In PHP, you would usually use isset(). In some cases, it could be ok if a parameter is not isset(). You probably want to use some default value instead. Note that default values are not beiing validated - that would not make sense.
A good example is a checkbox: you want to obtain a boolean value wether it is checked or not. However, from a HTML form, you usually don't receive any value when the checkbox is not checked.
//with HRC, you can easily get the checkbox value. $hrc->check("checkbox") ->setDefault(false) //optionally, you can validate the value sent ->addRule( HRC::BOOL ); // get boolean value - FALSE when not set, TRUE casted from the obtained string $checked = (bool) $hrc->get( "checkbox" );
It might be convenient to set a default value when working with arrays. If you send an empty array, you usually don't receive anything on the server side. If your controller wants to work with an empty array, just set it as a default value.
//if not set, use empty array $hrc->check("positiveNums") ->setDefault( array() ) ->addAIRule( HRC::INT, 0 );
By validating objects, we mean a PHP array where each attribute could be different and different validation rules for each attribute are applied.
You can either check for single objects but in case of multiple objects of the same type, it would probably make sense to check for an array of objects.
The data in JavaScript could look like this:
// data object var data = { myObjects : [ { name : "John", favouriteColors : [ "#FFFFFF", "#AAA000" ] }, { name : "Mark", favouriteColors : [ ] } // and so on ..... ] } //and now, you can send the variable data e.g. using AJAX...
In PHP, you can pretty easily set-up the rules to validate such structure:
//let's assume that $hrc object checking $_POST exists //now, we create a new HRC object to validate a single object in myObjects $personObject = $hrc->newInstance() //same effect as: new HRC("post") ->check("name") ->addRule( "strlen" ) //not empty ->check( "favouriteColors" ) ->setDefault( array() ) //validate each item in favouriteColors using regexp //as a hexadecimal color representation ->addAIRule( "preg_match", '/^#([0-9A-F]{3}){1,2}$/i'); //and now, it is very easy to validate the array of objects $hrc->check( "myObjects" ) //$personObject is used as a rule for every item in $_POST["myObjects"] ->addAIRule( $personObject ) //and for example, we could require at least two objects in the array ->addRule( "count", ">", 1);
As you could see, HRC object could be used as a rule for an object-structure. Additionaly, HRC can be used recursively.
A simply example could be maping/validating a binary tree: Each node has a value and up to two children nodes; leaf nodes have no children nodes.
The data in JavaScript could look like this:
// data object with a binary tree structure var data = { myBinaryTree : { injectedValue : "???" value: "10", leftChild : { value: 5, leftChild : { value: 2 } }, rightChild :{ value: 18, leftChild : { value: 12 }, rightChild :{ value: 22, leftChild : {value: 19}, rightChild :{value: 23} } } } } //and now, you can send the variable data e.g. using AJAX... //all the values are converted to strings
Let's set-up the validation rules
// new object for a tree node $node = new HRC(); $node->check("value") //and the value should be integer ->addRule(HRC::INT) ->check("leftChild") //might not be set - use default value for easier usage ->setDefault( null ) //apply the same rules for leftChild as for any other node = recursion ->addRule( $node ) //end the same for right child ->checkAlso("rightChild"); // Additionally, you can specify the maximum depth - amount of HRC objects used // The root node will have depth 1 $node->addRule( array($node, "getDepth"), "<", 5 ); //and now, we connect it to the root node - $_POST[ "myBinaryTree" ] $hrc->check( "myBinaryTree" )->addRule( $node );
Nota that, with these validation rules, every node will have leftChild and rightChild present, sometimes NULL (default value) and of course the attribute "value". If there are any other attributes, such as injectedValue, they are ignore because you just haven't asked or it.
....to be continued....
(trees)