PHP Class lithium\util\Validator

General data checking is done by using Validator statically. Rules can be specified as a parameter to the rule() method or accessed directly via the is[RuleName]() method name convention: {{{ use lithium\util\Validator; The following are equivalent: Validator::rule('email', '[email protected]'); // true Validator::isEmail('foo-at-example.com'); // false }}} Data can also be validated against multiple rules, each having their own associated error message. The rule structure is array-based and hierarchical based on rule names and messages. Responses match the keys present in the $data parameter of check() up with an array of rules which they violate. {{{ embed:lithium\tests\cases\util\ValidatorTest::testCheckMultipleHasFirstError(1-15) }}} See the check() method for more information an multi-value datasets. Custom validation rules can also be added to Validator at runtime. These can either take the form of regular expression strings or functions supplied to the add() method. ### Rules The Validator class includes a series of commonly-used rules by default, any of which may be used in calls to rule() or check(), or called directly as a method. Additionally, many rules have a variety of different _formats_ in which they may be specified. The following is the list of the built-in rules, but keep in mind that none of them are hard-coded. Any rule may be overridden by adding a new rule of the same name using the add() method. - notEmpty: Checks that a string contains at least one non-whitespace character. - alphaNumeric: Checks that a string contains only integer or letters. - lengthBetween: Checks that a string length is within a specified range. Spaces are included in the character count. The available options are 'min' and 'max', which designate the minimum and maximum length of the string. - blank: Checks that a field is left blank **OR** only whitespace characters are present in its value. Whitespace characters include spaces, tabs, carriage returns and newlines. - creditCard: Checks that a value is a valid credit card number. This rule is divided into a series of formats: 'amex', 'bankcard', 'diners', 'disc', 'electron', 'enroute', 'jcb', 'maestro', 'mc', 'solo', 'switch', 'visa', 'voyager', 'fast'. If no format value is specified, the value defaults to 'any', which will validate the value if _any_ of the available formats match. You can also use the 'fast' format, which does a high-speed, low-fidelity check to ensure that the value looks like a real credit card number. This rule includes one option, 'deep', which (if set to true) validates the value using the Luhn algorithm if the format validation is successful. See the luhn validator below for more details. - date: Checks that a value is a valid date that complies with one or more formats. Also validates leap years. Possible formats are 'dmy' (27-12-2010 or 27-12-10 separators can be a space, period, dash, forward slash), 'mdy' (12-27-2010 or 12-27-10 separators can be a space, period, dash, forward slash), 'ymd' (2010-12-27 or 10-12-27 separators can be a space, period, dash, forward slash), 'dMy' (27 December 2010 or 27 Dec 2010), 'Mdy' (December 27, 2010 or Dec 27, 2010 comma is optional), 'My' (December 2010 or Dec 2010) or 'my' (12/2010 separators can be a space, period, dash, forward slash). - time: Checks that a value is a valid time. Validates time as 24hr (HH:MM) or am/pm ([ H]H:MM[a|p]m). Does not allow / validate seconds. - boolean: Checks that the value is or looks like a boolean value. The following types of values are interpreted as boolean and will pass the check. - boolean (true, false, 'true', 'false') - boolean number (1, 0, '1', '0') - boolean text string ('on', 'off', 'yes', 'no') - decimal: Checks that a value is a valid decimal. Takes one option, 'precision', which is an optional integer value defining the level of precision the decimal number must match. - email: Checks that a value is (probably) a valid email address. The subject of validating an actual email address is complicated and problematic. A regular expression that correctly validates addresses against RFC 5322 would be several pages long, with the drawback of being unable to keep up as new top-level domains are added. Instead, this validator uses PHP's internal input filtering API to check the format, and provides an option, 'deep' ( _boolean_) which, if set to true, will validate that the email address' domain contains a valid MX record. Keep in mind, this is just one of the many ways to validate an email address in the overall context of an application. For other ideas or examples, ask Sean. - ip: Validates a string as a valid IPv4 or IPv6 address. - money: Checks that a value is a valid monetary amount. This rule has two formats, 'right' and 'left', which indicates which side the monetary symbol (i.e. $) appears on. - numeric: Checks that a value is numeric. - phone: Check that a value is a valid phone number, non-locale-specific phone number. - postalCode: Checks that a given value is a valid US postal code. - inRange: Checks that a numeric value is within a specified range. This value has two options, 'upper' and 'lower', which specify the boundary of the value. - url: Checks that a value is a valid URL according to RFC 2395. Uses PHP's filter API, and accepts any options accepted for the validation URL filter. - luhn: Checks that a value is a valid credit card number according to the Luhn algorithm. (See also: the creditCard validator). - inList: Checks that a value is in a pre-defined list of values. This validator accepts one option, 'list', which is an array containing acceptable values. - regex: Checks that a value appears to be a valid regular expression, possibly containing PCRE-compatible options flags. - uuid: Checks that a value is a valid UUID. ### UTF-8 encoded input strings All rules operating on strings have been created with the possibility of UTF-8 encoded input in mind. A default PHP binary and an enabled Lithium g11n bootstrap will make these rules work correctly in any case. Should you ever experience odd behavior following paragraph with implementation details might help you to track to the cause. The rules alphaNumeric and money rely on additional functionality of PCRE to validate UTF-8 encoded strings. As no PCRE feature detection is done, having this feature enabled in PCRE isn't optional. Please ensure you've got PCRE compiled with UTF-8 support.
Inheritance: extends lithium\core\StaticObject
Datei anzeigen Open project: unionofrad/lithium Class Usage Examples

Protected Properties

Property Type Description
$_options array Default options used when defining a new validator rule. Each key contains method-specific options that should always be applied, or options that should be applied to all rules in the 'defaults' key.
$_rules array An array of validation rules. May contain a single regular expression, an array of regular expressions (where the array keys define various possible 'formats' of the same rule), or a closure which accepts a value to be validated, and an array of options, and returns a boolean value, indicating whether the validation succeeded or failed.

Public Methods

Method Description
__callStatic ( string $method, array $args = [] ) : boolean Maps method calls to validation rule names. For example, a validation rule that would normally be called as Validator::rule('email', '[email protected]') can also be called as Validator::isEmail('[email protected]').
add ( mixed $name, string $rule = null, array $options = [] ) Adds to or replaces built-in validation rules specified in Validator::$_rules. Any new validation rules created are automatically callable as validation methods.
check ( array $values, array $rules, array $options = [] ) : array Checks a set of values against a specified rules list. This method may be used to validate any arbitrary array of data against a set of validation rules.
reset ( ) Initializes the list of default validation rules.
respondsTo ( string $method, boolean $internal = false ) : boolean Determines if a given method can be called.
rule ( string $rule, mixed $value, string $format = 'any', array $options = [] ) : boolean Checks a single value against a single validation rule in one or more formats.
rules ( string $name = null ) : mixed Returns a list of available validation rules, or the configuration details of a single rule.

Protected Methods

Method Description
_checkFormats ( array $rules ) : Closure Perform validation checks against a value using an array of all possible formats for a rule, and an array specifying which formats within the rule to use.

Method Details

__callStatic() public static method

Maps method calls to validation rule names. For example, a validation rule that would normally be called as Validator::rule('email', '[email protected]') can also be called as Validator::isEmail('[email protected]').
public static __callStatic ( string $method, array $args = [] ) : boolean
$method string The name of the method called, i.e. `'isEmail'` or `'isCreditCard'`.
$args array
return boolean

_checkFormats() protected static method

Perform validation checks against a value using an array of all possible formats for a rule, and an array specifying which formats within the rule to use.
protected static _checkFormats ( array $rules ) : Closure
$rules array All available rules.
return Closure Function returning boolean `true` if validation succeeded, `false` otherwise.

add() public static method

For example: Validator::add('zeroToNine', '/^[0-9]$/'); $isValid = Validator::isZeroToNine("5"); // true $isValid = Validator::isZeroToNine("20"); // false Alternatively, the first parameter may be an array of rules expressed as key/value pairs, as in the following: Validator::add(array( 'zeroToNine' => '/^[0-9]$/', 'tenToNineteen' => '/^1[0-9]$/', )); In addition to regular expressions, validation rules can also be defined as full anonymous functions: use app\models\Account; Validator::add('accountActive', function($value) { $value = is_int($value) ? Account::find($value) : $value; return (boolean) $value->is_active; }); $testAccount = Account::create(array('is_active' => false)); Validator::isAccountActive($testAccount); // returns false These functions can take up to 3 parameters: - $value _mixed_: This is the actual value to be validated (as in the above example). - $format _string_: Often, validation rules come in multiple "formats", for example: postal codes, which vary by country or region. Defining multiple formats allows you to retain flexibility in how you validate data. In cases where a user's country of origin is known, the appropriate validation rule may be selected. In cases where it is not known, the value of $format may be 'any', which should pass if any format matches. In cases where validation rule formats are not mutually exclusive, the value may be 'all', in which case all must match. - $options _array_: This parameter allows a validation rule to implement custom options.
See also: lithium\util\Validator::$_rules
public static add ( mixed $name, string $rule = null, array $options = [] )
$name mixed The name of the validation rule (string), or an array of key/value pairs of names and rules.
$rule string If $name is a string, this should be a string regular expression, or a closure that returns a boolean indicating success. Should be left blank if `$name` is an array.
$options array The default options for validating this rule. An option which applies to all regular expression rules is `'contains'` which, if set to true, allows validated values to simply _contain_ a match to a rule, rather than exactly matching it in whole.

check() public static method

Checks a set of values against a specified rules list. This method may be used to validate any arbitrary array of data against a set of validation rules.
public static check ( array $values, array $rules, array $options = [] ) : array
$values array An array of key/value pairs, where the values are to be checked.
$rules array An array of rules to check the values in `$values` against. Each key in `$rules` should match a key contained in `$values`, and each value should be a validation rule in one of the allowable formats. For example, if you are validating a data set containing a `'credit_card'` key, possible values for `$rules` would be as follows: - `array('credit_card' => 'You must include a credit card number')`: This is the simplest form of validation rule, in which the value is simply a message to display if the rule fails. Using this format, all other validation settings inherit from the defaults, including the validation rule itself, which only checks to see that the corresponding key in `$values` is present and contains a value that is not empty. _Please note when globalizing validation messages:_ When specifying messages, it may be preferable to use a code string (i.e. `'ERR_NO_TITLE'`) instead of the full text of the validation error. These code strings may then be translated by the appropriate tools in the templating layer. - `array('credit_card' => array('creditCard', 'message' => 'Invalid CC #'))`: In the second format, the validation rule (in this case `creditCard`) and associated configuration are specified as an array, where the rule to use is the first value in the array (no key), and additional settings are specified as other keys in the array. Please see the list below for more information on allowed keys. - The final format allows you to apply multiple validation rules to a single value, and it is specified as follows: `array('credit_card' => array( array('notEmpty', 'message' => 'You must include credit card number'), array('creditCard', 'message' => 'Your credit card number must be valid') ));`
$options array Validator-specific options. Each rule defined as an array can contain any of the following settings (in addition to the first value, which represents the rule to be used): - `'message'` _string_: The error message to be returned if the validation rule fails. See the note above regarding globalization of error messages. - `'required`' _boolean_: Represents whether the value is required to be present in `$values`. If `'required'` is set to `false`, the validation rule will be skipped if the corresponding key is not present. Defaults to `true`. - `'skipEmpty'` _boolean_: Similar to `'required'`, this setting (if `true`) will cause the validation rule to be skipped if the corresponding value is empty (an empty string or `null`). Defaults to `false`. - `'format'` _string_: If the validation rule has multiple format definitions (see the `add()` or `init()` methods), the name of the format to be used can be specified here. Additionally, two special values can be used: either `'any'`, which means that all formats will be checked and the rule will pass if any format passes, or `'all'`, which requires all formats to pass in order for the rule check to succeed.
return array Returns an array containing all validation failures for data in `$values`, where each key matches a key in `$values`, and each value is an array of that element's validation errors.

reset() public static method

Initializes the list of default validation rules.
public static reset ( )

respondsTo() public static method

Determines if a given method can be called.
public static respondsTo ( string $method, boolean $internal = false ) : boolean
$method string Name of the method.
$internal boolean Provide `true` to perform check from inside the class/object. When `false` checks also for public visibility; defaults to `false`.
return boolean Returns `true` if the method can be called, `false` otherwise.

rule() public static method

Checks a single value against a single validation rule in one or more formats.
public static rule ( string $rule, mixed $value, string $format = 'any', array $options = [] ) : boolean
$rule string
$value mixed
$format string
$options array
return boolean Returns `true` or `false` indicating whether the validation rule check succeeded or failed.

rules() public static method

Returns a list of available validation rules, or the configuration details of a single rule.
public static rules ( string $name = null ) : mixed
$name string Optional name of a rule to get the details of. If not specified, an array of all available rule names is returned. Otherwise, returns the details of a single rule. This can be a regular expression string, a closure object, or an array of available rule formats made up of string regular expressions, closures, or both.
return mixed Returns either an single array of rule names, or the details of a single rule.

Property Details

$_options protected_oe static_oe property

Default options used when defining a new validator rule. Each key contains method-specific options that should always be applied, or options that should be applied to all rules in the 'defaults' key.
See also: lithium\util\Validator::add()
See also: lithium\util\Validator::rule()
protected static array $_options
return array

$_rules protected_oe static_oe property

An array of validation rules. May contain a single regular expression, an array of regular expressions (where the array keys define various possible 'formats' of the same rule), or a closure which accepts a value to be validated, and an array of options, and returns a boolean value, indicating whether the validation succeeded or failed.
See also: lithium\util\Validator::add()
See also: lithium\util\Validator::rule()
protected static array $_rules
return array