Validator Class
CodeDmx has a Validator class. This class can help you to validate inputs, form, or data that you sent.
Note
If you want to create your own validators functions, you can disable this class, only comment the class that you don't want to use on /Model/Loader.php
- First of all: A simple example
- Available Methods
- Long format example
- Creating your own validators and filters
- Available Validators
- Available Filters
- Validate file fields
- URL Exists (Example)
- Validate street address (Example)
- Sanitize string (Example)
- Match strings (Example)
- Escaping Mysql Strings (Example)
- Custom validator (Example)
First of all: A simple example
Before to explain this example, let's to describe the ideal scenario:
- A form is displayed
- The user fill it and submit
Runs the validation of the form submited:
$is_valid = $this->validate->is_valid($_POST, array(
'username' => 'required|alpha_numeric',
'password' => 'required|max_len,100|min_len,6'
));
if ($is_valid === TRUE)
{
//continue
}
else
{
print_r($is_valid);
}
Available Methods
This are all available methods of Validator Class
// The short way to validate
is_valid(array $data, array $rules);
// Get or set the validation rules
validation_rules(array $rules);
// Get or set the filtering rules
filter_rules(array $rules);
// Run the filter and validation routines
run(array $data);
// Strips and encodes unwanted characters
xss_clean(array $data);
// Sanitizes data and converts strings to UTF-8, this isn't required, but it's safest to do so.
sanitize(array $input);
// Validates input data according to the provided rules
validate(array $input, array $rules);
// Filters input data according to the provided filter
filter(array $input, array $filter);
// Returns human readable error text in an array or string
get_readable_errors($convert_to_string = false);
// Fetch an array of validation errors indexed by the field names
get_errors_array();
// Override field names with readable ones for errors
set_field_name($field, $readable_name);
Long format example
Runs the validation of the form submited:
$_POST = $this->validate->sanitize($_POST); // You don't have to do this, but it's safest to do.
$this->validate->validation_rules(array(
'username' => 'required|alpha_numeric|max_len,20|min_len,6',
'password' => 'required|max_len,100|min_len,6',
'email' => 'required|valid_email'
));
$this->validate->filter_rules(array(
'username' => 'trim|sanitize_string',
'password' => 'trim',
'email' => 'trim|sanitize_email'
));
$validated_data = $this->validate->run($_POST);
if ($validated_data === FALSE)
{
echo $this->get_readable_errors(TRUE);
}
else
{
print_r($validated_data); // validation successful
}
Creating your own validators and filters
Adding custom validators and filters is made easy by using callback functions.
/*
Create a csutom validation rule named "is_object".
This callback receives 3 arguments:
The field to validate, the values being validated, and any parameters used in the validation rule.
It sould return a boolean value indicating whether the value is valid.
*/
$this->validate->add_validator('is_object', function($field, $input, $param = NULL) {
return is_object($input[$field]);
});
/*
Create a custom filter named "upper".
The callback function receives two arguments:
The value to filter, and any parameters used in the filter rule. It should returned the filtered value.
*/
$this->validate->add_filter('upper', function($value, $param = NULL) {
return strtoupper($value);
});
Available Validators
The followin is a list of all the native rules that are available to use:
| Rule | Description | Parameter |
|---|---|---|
| required | Check the specified key value exists and is not empty | |
| equalsfield,n | Check if math with another field value | n = name of the field value |
| valid_email | Checks for a valid email address | |
| max_len,n | Checks value length, makes sure it's not longer than the specified length | n = length |
| min_len,n | Checks value length, makes sure it's not shorter than the specified length | n = length |
| exact_len,n | Check that the value length precisely matches the specified length | n = length |
| alpha | Check that only alpha characters are present in the value (a-z, A-Z) | |
| alpha_numeric | Check that only alpha-numeric characters are present in the value (a-z, A-Z, 0-9) | |
| alpha_dash | Check that only alpha-numeric characters + dashes and underscores are present in the value (a-z, A-Z, 0-9, _-) | |
| alpha_space | Check that only alpha-numeric characters + spaces are present in the value (a-z, A-Z, 0-9, \s) | |
| numeric | Check that only numeric values | |
| integer | Check that only integer values | |
| boolean | Checks for PHP accepted boolean values, returns TRUE for "1", "true", "on" and "yes" | |
| float | Checks for float values | |
| valid_url | Check for valid URL or subdomain | |
| url_exists | Check to see if the url exists and is accessible | |
| valid_ip | Check for valid generic IP address | |
| valid_ipv4 | Check for valid IPv4 address | |
| valid_ipv6 | Check for valid IPv6 address | |
| valid_cc | Check for a valid credit card number (Uses the MOD10 Checksum Algorithm) | |
| valid_name | Check for a valid format human name | |
| contains,n | Verify that a value is contained within the pre-defined value set | n = value |
| contains_list,n | Verify that a value is contained within the pre-defined value set. The list of valid values must be provided in semicolon-separated list format (like: value1;value2;value3;..;valuen). If a validation error occurs, the list of valid values is not revelead (this means, the error will just say the input is invalid, but it won't reveal the valid set to the user). | n = value |
| doesnt_contain_list,n | Verify that a value is not contained within the pre-defined value set. Semicolon (;) separated, list not outputted. | n = value |
| street_address | Checks that the provided string is a likely street address. 1 number, 1 or more space, 1 or more letters | |
| iban | Check for a valid IBAN | |
| min_numeric | Determine if the provided numeric value is higher or equal to a specific value | |
| max_numeric | Determine if the provided numeric value is lower or equal to a specific value | |
| date | Determine if the provided input is a valid date (ISO 8601) | |
| starts | Ensures the value starts with a certain character / set of character | |
| phone_number | Validate phone numbers that match the following examples: 555-555-5555 , 5555425555, 555 555 5555, 1(519) 555-4444, 1 (519) 555-4422, 1-555-555-5555 | |
| regex,/your-regex/ | You can pass a custom regex using the following format: 'regex,/your-regex/' | your-regex = regex that you preffer to validate |
| valid_json_string | Validate string to check if it's a valid json format |
Available Filters
Filters can be any PHP function that returns a string. You don't need to create your own if a PHP function exists that does what you want the filter to do.
| Rule | Description |
|---|---|
| sanitize_string | Remove script tags and encode HTML entities, similar to $this->validate->xss_clean(); |
| urlencode | Encode url entities |
| htmlencode | Encode HTML entities |
| sanitize_email | Remove illegal characters from email addresses |
| sanitize_numbers | Remove any non-numeric characters |
| sanitize_floats | Remove any non-float characters |
| trim | Remove spaces from the beginning and end of strings |
| base64_encode | Base64 encode the input |
| base64_decode | Base64 decode the input |
| sha1 | Encrypt the input with the secure sha1 algorithm |
| md5 | MD5 encode the input |
| noise_words | Remove noise words from string |
| json_encode | Create a json representation of the input |
| json_decode | Decode a json string |
| rmpunctuation | Remove all known punctuation characters from a string |
| basic_tags | Remove all layout orientated HTML tags from text. Leaving only basic tags |
| whole_number | Check that the provided numeric value is represented as a whole number |
Validate file fields
When you use a form that want to upload files, you can validate the file too
$is_valid = $this->validate->is_valid(array_merge($_POST, $_FILES), array(
'title' => 'required|alpha_numeric',
'image' => 'required_file|extension,png;jpg'
));
if ($is_valid === TRUE)
{
//continue
}
else
{
print_r($is_valid);
}
URL Exists (Example)
$_POST = array(
'url' => 'http://asidnqowineoqiwneoinspoqwehpi1.com' // This url doesn't exist
);
$rules = array(
'url' => 'url_exists'
);
$is_valid = $this->validate->validate($_POST, $rules);
if ($is_valid === TRUE)
{
echo 'The URL provided is valid';
}
else
{
print_r($this->validate->get_readable_errors());
}
Validate street address (Example)
$data = array(
'street' => 'Kuwait 6958'
);
$validate = $this->validate->is_valid($data, array(
'street' => 'required|street_address'
));
if ($validate === TRUE)
{
echo 'Valid Street Address';
}
else
{
print_r($validate);
}
Sanitize string (Example)
$_POST = array(
'string' => '<script>alert(1); $("body").remove(); </script>'
);
$filter = array(
'string' => 'sanitize_string'
);
print_r($this->validate->filter($_POST, $filter));
Match strings (Example)
$data = array(
'username' => 'myusername',
'password' => 'mypassword',
'password_confirm' => 'mypa33word'
);
$is_valid = $this->validate->is_valid($data, array(
'username' => 'required|alpha_numeric',
'password' => 'required|max_len,100|min_len,6',
'password_confirm' => 'equalsfield,password'
));
if ($is_valid === TRUE)
{
// continue
}
else
{
print_r($is_valid);
}
Escaping Mysql Strings (Example)
$_POST = array(
'username' => 'my username',
'password' => "' OR ''='"
);
$this->validate->sanitize($_POST);
$filter = array(
'username' => 'noise_words',
'password' => 'trim|strtolower|addslashes'
);
print_r($this->validate->filter($_POST, $filter));
Custom validator (Example)
// Add the custom validator
$this->validate->add_validator('is_object', function($field, $input, $param = NULL) {
return is_object($input[$field]);
});
// Generic data
$input_data = array(
'not_object' => 'asdqwezxc',
'valid_object' => new stdClass()
);
$rules = array(
'not_object' => 'is_object',
'valid_object' => 'is_object'
);
/*
Long Method
*/
$validated = $this->validate->validate(
$input_data, $rules
);
if ($validated === TRUE)
{
echo 'Validation passed!';
}
else
{
echo $this->validate->get_readable_errors(TRUE);
}
/*
Short Method
*/
$is_valid = $this->validate->is_valid($input_data, $rules);
if ($is_valid === TRUE)
{
echo 'Validation passed!';
}
else
{
print_r($is_valid);
}