FastSitePHP\Data\Validator

FastSitePHP Data Validation API

For many apps validating client side (webpage or app) provides instant feedback to users and limits need for extra web request, however users can bypass validation by using DevTools or other methods so for data that needs to be validated using server-side validation is important.

This class allows for many rules to be easily defined and run against an object (or Associative Array/Dictionary).

Common rules can simply be copied from HTML Input controls.

Source Code

GitHub

رمز المثال

Validating User Input

// For many apps validating client side (webpage or app) provides instant
// feedback to users and limits need for extra web request, however users
// can bypass validation by using DevTools or other methods so for data
// that needs to be validated using server-side validation is important.

// FastSitePHP provides a class that allows for many rules to be easily
// defined and run against an object (or Associative Array/Dictionary).

// Common rules can simply be copied from HTML Input controls.

// HTML Example:
/*
    <input name="name" title="Name" required>
    <input name="age" title="Age" required min="13" max="99">
    <input name="phone" title="Phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
*/

// FastSitePHP Code to Validate Form Post using the above HTML.
// Form Post Fields come in the PHP Superglobal array [$_POST]
// and it can simply be passed to the [Validator] class.
$v = new \FastSitePHP\Data\Validator();
$v->addRules([
    // Field,  Title,   Rules
    ['name',  'Name',  'required'],
    ['age',   'Age',   'required min="13" max="99"'],
    ['phone', 'Phone', 'pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"'],
]);
list($errors, $fields) = $v->validate($_POST);
if ($errors) {
    // Error Logic
    // [$errors] returns an array of error messages for the end user
    // [$fields] returns an array of unique fields that had an error
    // along with an array of error messages for each field.
    // Fields can be used by a client app to highlight form fields, etc.
}

// In addition to using strings for the rules you can also use arrays.
// This can provide better performance if you have a high traffic site,
// however it runs very fast either way.
$v = new \FastSitePHP\Data\Validator();
$v->addRules([
    ['name',  'Name',  ['required' => true]],
    ['age',   'Age',   [
        'required' => true,
        'min' => '13',
        'max' => '99',
    ]],
    ['phone', 'Phone', ['pattern' => '[0-9]{3}-[0-9]{3}-[0-9]{4}']],
]);

// The validator class supports a number of HTML5 rules along
// with some custom rules:
//     'exists', 'required', 'type', 'minlength', 'maxlength',
//     'length', 'min', 'max', 'pattern', 'list',

// The [type] rule supports a number of HTML5 data types along
// with many custom data types:
//      'text', 'password', 'tel', 'number', 'range', 'date',
//      'time', 'datetime', 'datetime-local', 'email', 'url',
//      'unicode-email', 'int', 'float', 'json', 'base64',
//      'base64url', 'xml', 'bool', 'timezone', 'ip', 'ipv4',
//      'ipv6', 'cidr', 'cidr-ipv4', 'cidr-ipv6',

// In addition to standard rules custom rules can be defined using
// callback functions that return true/false or a custom error
// message string:
$v
    ->addRules([
        ['site_user',     'Site User', 'check-user required'],
        ['site_password', 'Password',  'check-password required'],
    ])
    ->customRule('check-user', function($value) {
        return ($value === 'admin');
    })
    ->customRule('check-password', function($value) {
        return ($value === 'secret' ? true : 'Invalid Password');
    });

list($errors, $fields) = $v->validate($_POST);

Methods

addRules(array $rules)

Add an array of rules for use with the [validation()] function in the format of [Field, Display_Name, Rules].

Field = String of the Array Key or Object Property to validate Display_Name = Field Name to include on Error Text for User - String or Null to use Field Name Rules = String of rules to be parsed or an array of defined rules

Returns: $this

customRule($name, \Closure $callback)

Define a Custom Rule using a callback function for use with the [validation()] function.

The name must contain a dash '-' character and cannot contain spaces [ ], quotes ["], or equals [=] characters.

Examples of valid rule names:
    'custom-rule'
    'check-password'
    'db-unique-email'

Returns: $this

supportedRules()

Return an array of standard rules supported by this class.

Returns: array

supportedTypes()

Return an array of types supported the [type] rule.

Returns: array

errorText(array $error_text = null)

Getter / Setter Property

Get or set an Array of error message templates used when validation fails. All error text can be overridden by the calling application.

Different data types for the [type] validation can have specific messages under the 'types' option. See a full list of types in the function [supportedTypes()].

To customize text for your applications simply copy and modify the array from this function's source code.

Returns: array | $this

validate($data)

Validate an object using rules defined from [addRules() or customRule()].

The object to validate, must be either an Associative Array (Dictionary) or an Object

Returns an array of ( error_messages[], error_fields[] ) where
    error_messages[] = Error Messages to Display to End Users
    error_fields[]   = Dictionary with each field that had an error and an array of error messages for the field. If count(error_messages[]) = 0 then all validations passed.

Returns: array

checkType($value, $type)

Return [true] if valid - Value matches the specified data type.

This function is marked public for validation with Unit Testing. Calling [validate()] after [addFields(), etc] is the intended use of this class.

Returns: bool