PHPasap provides a very simple and extendable Validation library to validate any kind of data. Usually you would be using the validation library to validate the data received from a user submitted form.
Form validation library works on rules. You define a rule or a group of rule for a field. Form validation library check if the provided field satisfies the defined rule. If any error occurs then validation fails.
Below is an example usage of the Form Validation
$data = [ "first_name" => "John", "last_name" => "Doe", "website" => "", ]; //Usually $data will be $_POST $rules = [ "first_name" => ["required", "First name"], "last_name" => ["required", "Last name"], "website" => ["required|url", "Website link"], ]; if( !Validator::validate($data, $rules) ) { //validation failed $error_array = Validator::errors(); } else { //validation successful }
The validate()
method accepts two paramters. First is the data (in array format) that has to be validated and the second is the array of rules to check the data against
If validation is successful then validate()
returns boolean true. If any errors then it returns boolean false.
Rules array has to be an associative array. Each key in this array is the name of the field that has to be validated for. While the value is another numeric array. First element is the rule and second one is the human readable name of the field that will be used by the validation library in the error message.
So say the age
field is suppose to be numeric. Then rule to be passed would be
"age" => ["numeric", "Age"]
Refer table below for the list of rules
To apply multiple rules to a field separate each rule by a pipe |
. So say age
is required and has to be numeric, then below is the rule to be defined for it.
"age" => ["required|numeric", "Age"]
Sometimes you may want to add your own custom rules to predefined ones. Like say username
should be unique. Let's say we want to add our custom rule unique_username. First we'll add below rule to the rules array
"username" => ["unique_username", "Username"]
The validation library will first check if the unique_username
exists in its predefined list of validation rules. If not then it will one by one do the following until it finds the callback function/method having this name
validate()
method is an object. Validation library will check if this object has any method with the same name unique_username
. If method exists it will call that method on the supplied object.unique_username
, then PHPasap will check if there exists a function unique_username()
. If it exists, then it calls that functionWhile calling the callback method/function the validator will call with below two arguments and optional third argument
unique_username
you provide unique_username:3
then validator will send value 3
as third param.Both methods are explained below
Remember the Controller method will be called only if the third param to validate method is the controller object. So below is how you would call the validate()
method
$rules = [ "first_name" => ["required", "First name"], "last_name" => ["required", "Last name"], "website" => ["required|url", "Website link"], "username" => ["required|unique_username", "Username"] //unique_username is our custom rule ]; //notice use of $this in third param if( !Validator::validate($data, $rules, $this) ) { //validation failed $error_array = Validator::errors(); } else { //validation successful }
Now in the same controller create below method
public function unique_username($validator_obj, $username_value) { if( DB::table("users")->where("username", "=", $username_value)->count() > 0 ) //username already in use $validator_obj->set_error("username", "Username already in use"); }
This option will be called if the third param of validate()
method is not set. Else if set with an object, the object should not have a method with callback function name.
if( !Validator::validate($data, $rules) { //notice third param is missing here unlike above example //validation failed $error_array = Validator::errors(); } else { //validation successful }
Now in any of the helpers file create the function unique_username
. Remember all helpers file in app/helpers
are autoloaded.
function unique_username($validator_obj, $username_value) { if( DB::table("users")->where("username", "=", $username_value)->count() > 0 ) //username already in use $validator_obj->set_error("username", "Username already in use"); }
Few things to note here
set_error()
method of Validator_Handler object, which is the first param passed, to set error message, if any error.Usually when form validation fails you would redirect user to another page, mostly the page containing submitted form, with all the inputs he had filled. Below is how you would do so.
return Request::redirect_to("form-page")->with_inputs();
Here with_inputs()
would flash the user submitted data in Session which would then be used by the form library to autofill the user form. So for the form to autopopulate user entered data after error make sure you are using the Form class instead of using the HTML input fields directly. Refer the Request section for more details on redirecting user.
Below is the list of predefined rules
Rule | Description |
---|---|
required | Checks if given parameter exists and is not empty() |
set | Checks if given parameter exists. Will validate true even if field value is 0 or null |
Checks if given parameter value is a valid email | |
max | Eg usage: max:5 Check if length of string is less than given integer |
min | Eg usage: min:5 Check if length of string is greater than given integer |
regex | Eg usage: regex:/^[A-Za-z][A-Za-z0-9]{5,31}$/ Note that syntax is regex: followed by the regular expression. The first colon : after word regex is part of the syntax. |
numeric | Checks if given parameter has numeric value. So 22.55 , "22.55" , 22.5 would be valid values whereas "22Ab55" would be invalid. |
alnum | Checks if given parameter contains only alphanumeric characters. So 22.55 , "22ABC5" would be valid values whereas "a$b" , "22.55" would be invalid. Note how a float value 22.55 is considered valid but the string type of same value is invalid. |
natural | Checks if given parameter has positive natural number i.e 0,1,2,3... |
float | Checks if given parameter is of type float. So 23.55 will pass validation however "23.55" , 23 , "23" will fail validation. |
url | Checks if given parameter value is a valid url |