lithium\util\Validator::add()

public static method

Adds to or replaces built-in validation rules specified in Validator::$_rules. Any new validation rules created are automatically callable as validation methods.

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.

Parameters

  • mixed $name

    The name of the validation rule (string), or an array of key/value pairs of names and rules.

  • string $rule

    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.

  • array $options

    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.

Source

	public static function add($name, $rule = null, array $options = array()) {
		if (!is_array($name)) {
			$name = array($name => $rule);
		}
		static::$_rules = Set::merge(static::$_rules, $name);

		if (!empty($options)) {
			$options = array_combine(array_keys($name), array_fill(0, count($name), $options));
			static::$_options = Set::merge(static::$_options, $options);
		}
	}