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.
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. |