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.
 public static function __init(array $options = array())
 {
     parent::__init($options);
     $self = static::_instance();
     $self->_finders['count'] = function ($self, $params, $chain) use(&$query, &$classes) {
         $db = Connections::get($self::meta('connection'));
         $records = $db->read('SELECT count(*) as count FROM posts', array('return' => 'array'));
         return $records[0]['count'];
     };
     Post::applyFilter('save', function ($self, $params, $chain) {
         $post = $params['record'];
         if (!$post->id) {
             $post->created = date('Y-m-d H:i:s');
         } else {
             $post->modified = date('Y-m-d H:i:s');
         }
         $params['record'] = $post;
         return $chain->next($self, $params, $chain);
     });
     Validator::add('isUniqueTitle', function ($value, $format, $options) {
         $conditions = array('title' => $value);
         // If editing the post, skip the current psot
         if (isset($options['values']['id'])) {
             $conditions[] = 'id != ' . $options['values']['id'];
         }
         // Lookup for posts with same title
         return !Post::find('first', array('conditions' => $conditions));
     });
 }
 public static function init()
 {
     $class = __CLASS__;
     Validator::add('modelIsSet', function ($value, $format, $options) use($class) {
         if (isset($options['model']) && ($options['model'] = $class)) {
             return true;
         }
         return false;
     });
 }
Beispiel #3
0
 public function testMultipleLocales()
 {
     $data = '/phone en_US/';
     Catalog::write('runtime', 'validation.phone', 'en_US', $data);
     $data = '/phone en_GB/';
     Catalog::write('runtime', 'validation.phone', 'en_GB', $data);
     Validator::add('phone', array('en_US' => Catalog::read('runtime', 'validation.phone', 'en_US'), 'en_GB' => Catalog::read('runtime', 'validation.phone', 'en_GB')));
     $result = Validator::isPhone('phone en_US', 'en_US');
     $this->assertTrue($result);
     $result = Validator::isPhone('phone en_GB', 'en_GB');
     $this->assertTrue($result);
 }
 public static function __init(array $options = array())
 {
     parent::__init($options);
     $self = static::_instance();
     Comment::applyFilter('save', function ($self, $params, $chain) {
         $comment = $params['record'];
         if (!$comment->id) {
             $comment->created = date('Y-m-d h:i:s');
         } else {
             $comment->modified = date('Y-m-d h:i:s');
         }
         $params['record'] = $comment;
         return $chain->next($self, $params, $chain);
     });
     Validator::add('validName', '/^[A-Za-z0-9\'\\s]+$/');
 }
Beispiel #5
0
 Validator::add('unique', function ($value, $format, $options) {
     $options += array('conditions' => array(), 'getEntityManager' => 'getEntityManager', 'connection' => isset($options['model']::$connectionName) ? $options['model']::$connectionName : 'default', 'checkPrimaryKey' => true);
     $entityManager = null;
     if (!empty($options['getEntityManager']) && method_exists($options['model'], $options['getEntityManager']) && is_callable($options['model'] . '::' . $options['getEntityManager'])) {
         $entityManager = call_user_func($options['model'] . '::' . $options['getEntityManager']);
     } elseif (!empty($options['connection'])) {
         $entityManager = lithium\data\Connections::get($options['connection'])->getEntityManager();
     }
     if (!$entityManager) {
         throw new \lithium\core\ConfigException('Could not get the entity manager');
     }
     $conditions = array($options['field'] => $value) + $options['conditions'];
     $query = $entityManager->createQueryBuilder();
     $expressions = array();
     $p = 1;
     foreach ($conditions as $field => $value) {
         $expressions[] = $query->expr()->eq('m.' . $field, '?' . $p);
         $query->setParameter($p, $value);
         $p++;
     }
     if ($options['checkPrimaryKey'] && !empty($options['values'])) {
         $metaData = $entityManager->getClassMetadata($options['model']);
         foreach ($metaData->identifier as $field) {
             if (isset($options['values'][$field])) {
                 $expressions[] = $query->expr()->neq('m.' . $field, '?' . $p);
                 $query->setParameter($p, $options['values'][$field]);
                 $p++;
             }
         }
     }
     $query->add('select', 'count(m.' . $options['field'] . ') total')->add('from', $options['model'] . ' m')->add('where', call_user_func_array(array($query->expr(), 'andx'), $expressions));
     $result = $query->getQuery()->getSingleResult();
     return empty($result['total']);
 });
Beispiel #6
0
Validator::add(array('sha1' => '/^[A-Fa-f0-9]{40}$/', 'slug' => '/^[a-z0-9\\_\\-\\.]*$/', 'loose_slug' => '/^[a-zA-Z0-9\\_\\-\\.]*$/', 'strict_slug' => '/^[a-z][a-z0-9\\_\\-]*$/', 'isUnique' => function ($value, $format, $options) {
    $conditions = array($options['field'] => $value);
    foreach ((array) $options['model']::meta('key') as $field) {
        if (!empty($options['values'][$field])) {
            $conditions[$field] = array('!=' => $options['values'][$field]);
        }
    }
    $fields = $options['field'];
    $result = $options['model']::find('first', compact('fields', 'conditions'));
    return (bool) empty($result);
}, 'status' => function ($value, $format, $options) {
    return (bool) $options['model']::status($value);
}, 'type' => function ($value, $format, $options) {
    return (bool) $options['model']::types($value);
}, 'md5' => function ($value, $format, $options) {
    return (bool) (strlen($value) === 32 && ctype_xdigit($value));
}, 'attachmentType' => function ($value, $type, $data) {
    if (!isset($data['attachment'])) {
        return true;
    }
    $mime = $data['attachment']['type'];
    $mimeTypes = Mime::types();
    foreach ($data['types'] as $each) {
        if (isset($mimeTypes[$each]) && in_array($mime, $mimeTypes[$each])) {
            return true;
        }
    }
    return false;
}, 'attachmentSize' => function ($value, $type, $data) {
    if (!isset($data['attachment'])) {
        return true;
    }
    $size = $data['attachment']['size'];
    if (is_string($data['size'])) {
        if (preg_match('/([0-9\\.]+) ?([a-z]*)/i', $data['size'], $matches)) {
            $number = $matches[1];
            $suffix = $matches[2];
            $suffixes = array("" => 0, "Bytes" => 0, "KB" => 1, "MB" => 2, "GB" => 3, "TB" => 4, "PB" => 5);
            if (isset($suffixes[$suffix])) {
                $data['size'] = round($number * pow(1024, $suffixes[$suffix]));
            }
        }
    }
    return $data['size'] >= $size;
}));
Beispiel #7
0
 *		'width' => 45,
 *		'height' => 45,
 *		'message'   => 'The image dimensions must be 45 x 45'
 *         ]
 *     ]
 * ];
 * }}}
 *
 * If the field is set to `null`, this means the user intends to delete it so it would return `true`.
 */
Validator::add('dimensions', function ($value, $rule, $options) {
    $status = [];
    $field = $options['field'];
    if ($options['required'] && empty($_FILES[$field]['tmp_name'])) {
        return false;
    }
    if ($options['skipEmpty'] && empty($_FILES[$field]['tmp_name'])) {
        return true;
    }
    if (!isset($_FILES[$options['field']]['error']) && null === $_FILES[$options['field']]) {
        return true;
    }
    list($width, $height, $type, $attr) = getimagesize($_FILES[$field]['tmp_name']);
    if (isset($options['width']) && $width !== $options['width']) {
        $status[] = false;
    }
    if (isset($options['height']) && $height !== $options['height']) {
        $status[] = false;
    }
    return !in_array(false, $status, true);
});
Beispiel #8
0
 * locale dependent rules into the by specifying them manually or retrieving
 * them with the `Catalog` class.
 *
 * Enables support for multibyte strings through the `Multibyte` class by
 * overwriting rules (currently just `lengthBetween`).
 *
 * @see lithium\g11n\Catalog
 * @see lithium\g11n\Multibyte
 * @see lithium\util\Validator
 */
foreach (array('phone', 'postalCode', 'ssn') as $name) {
    Validator::add($name, Catalog::read(true, "validation.{$name}", 'en_US'));
}
Validator::add('lengthBetween', function ($value, $format, $options) {
    $length = Multibyte::strlen($value);
    $options += array('min' => 1, 'max' => 255);
    return $length >= $options['min'] && $length <= $options['max'];
});
/**
 * In-View Translation
 *
 * Integration with `View`. Embeds message translation aliases into the `View`
 * class (or other content handler, if specified) when content is rendered. This
 * enables translation functions, i.e. `<?=$t("Translated content"); ?>`.
 *
 * @see lithium\g11n\Message::aliases()
 * @see lithium\net\http\Media
 */
Media::applyFilter('_handle', function ($self, $params, $chain) {
    $params['handler'] += array('outputFilters' => array());
    $params['handler']['outputFilters'] += Message::aliases();
Beispiel #9
0
/**
 * Works same as Lithium's `inRange` validator but require conditions `true` to continue
 * @see \li3_validators\extensions\util\EvalComparation::build()
 */
$customValidators['conditionalInRange'] = function ($value, $format, $options) {
    $options += array('upper' => null, 'lower' => null, 'conditions' => array());
    $conditions = true;
    if (!is_numeric($value)) {
        return false;
    }
    if (!empty($options['conditions'])) {
        $conditions = eval(EvalComparation::build($options));
        if (!$conditions) {
            return true;
        }
    }
    switch (true) {
        case !is_null($options['upper']) && !is_null($options['lower']):
            return $value > $options['lower'] && $value < $options['upper'];
        case !is_null($options['upper']):
            return $value < $options['upper'];
        case !is_null($options['lower']):
            return $value > $options['lower'];
    }
    return is_finite($value);
};
/**
 * Initialize custom validators
 */
Validator::add($customValidators);
 * Integration with `View`. Embeds message translation aliases into the `View`
 * class (or other content handler, if specified) when content is rendered. This
 * enables translation functions, i.e. `<?=$t("Translated content"); ?>`.
 */
Media::applyFilter('_handle', function ($self, $params, $chain) {
    $params['handler'] += array('outputFilters' => array());
    $params['handler']['outputFilters'] += Message::aliases();
    return $chain->next($self, $params, $chain);
});
/**
 * Integration with `Validator`. You can load locale dependent rules into the `Validator`
 * by specifying them manually or retrieving them with the `Catalog` class.
 */
Validator::add('phone', Catalog::read('validation.phone', 'en_US'));
Validator::add('postalCode', Catalog::read('validation.postalCode', 'en_US'));
Validator::add('ssn', Catalog::read('validation.ssn', 'en_US'));
/**
 * Intercepts dispatching processes in order to set the effective locale by using
 * the locale of the request or if that is not available retrieving a locale preferred
 * by the client.
 */
ActionDispatcher::applyFilter('_callable', function ($self, $params, $chain) {
    $request = $params['request'];
    $controller = $chain->next($self, $params, $chain);
    if (!$request->locale) {
        $request->params['locale'] = Locale::preferred($request);
    }
    Environment::set(Environment::get(), array('locale' => $request->locale));
    return $controller;
});
ConsoleDispatcher::applyFilter('_callable', function ($self, $params, $chain) {
 public function testNlNl()
 {
     Validator::add(Catalog::read('validation', 'nl_NL'));
     $this->assertTrue(Validator::isSsn('123456789'));
     $this->assertFalse(Validator::isSsn('12345678'));
 }
<?php

use lithium\util\Validator;
Validator::add('uniqueName', function ($value, $format, $options) {
    $model = "\\" . $options['model'];
    //return !(boolean) $model::first(array('conditions' => array('name' => $options['values']['name'])));
    return true;
});
Beispiel #13
0
 *  `'mx'` boolean that enable validator to check if MX DNS record exists and
 *  `'pattern'` mixed `false` to use `filter_var()` function (default in lithium)
 * or regex to check against. By default this filter check against custom regex
 * that doesn't match all [RFC 5322](http://tools.ietf.org/html/rfc5322) valid
 * emails, but will match against most correct emails, and doesn't check domain
 * against MX DNS record. With combinations of this options you can achieve
 * enough validations, including lithium's default (`'mx' => false, 'pattern' => false`).
 */
$overriddenValidators['email'] = function ($value, $format, $options) {
    $defaults = array('mx' => false, 'pattern' => '/^[a-z0-9][a-z0-9_.-]*@[a-z0-9.-]{3,}\\.[a-z]{2,4}$/i');
    $options += $defaults;
    $valid = true;
    switch ($options['pattern']) {
        case false:
            $valid = filter_var($value, FILTER_VALIDATE_EMAIL);
            break;
        default:
            $valid = preg_match($options['pattern'], $value);
            break;
    }
    if ($valid && $options['mx'] && function_exists('checkdnsrr')) {
        $emailParts = explode('@', $value);
        $valid = checkdnsrr(end($emailParts), 'MX');
    }
    return $valid;
};
/**
 * Initialize overridden validators
 */
Validator::add($overriddenValidators);
Beispiel #14
0
});
Uploads::applyFilter('save', function ($self, $params, $chain) {
    if ($params['data']) {
        $params['entity']->set($params['data']);
        $params['data'] = array();
    }
    if (!$params['entity']->id) {
        $params['entity']->created = date('Y-m-d H:i:s');
    }
    return $chain->next($self, $params, $chain);
});
use lithium\util\Validator;
Validator::add('usernameTaken', function ($value) {
    $success = false;
    if (strlen($value) != 0) {
        $success = count(Users::findByUsername($value)) == 0 ? false : true;
    }
    return !$success;
});
use lithium\core\Libraries;
Libraries::add('upload', array('path' => LITHIUM_APP_PATH . '/libraries/_source/upload/'));
Libraries::add('captcha', array('path' => LITHIUM_APP_PATH . '/libraries/_source/captcha/', 'webroot' => LITHIUM_APP_PATH . '/libraries/_source/captcha/', "bootstrap" => "securimage.php"));
define('_INSTALL', file_exists($_SERVER['DOCUMENT_ROOT'] . "/install") ? '1' : '0');
function getBaseUrl()
{
    $protocol = isset($_SERVER["HTTPS"]) && $_SERVER['HTTPS'] != "off" ? "https" : "http";
    return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
use lithium\core\Environment;
Environment::is(function ($request) {
    return in_array($request->env('SERVER_ADDR'), array('::1', '127.0.0.1')) ? 'development' : 'production';
 /**
  * Tests that setting the `'contain'` rule option to false correctly requires a string to be
  * an exact match of the regex, with no additional characters outside.
  *
  * @return void
  */
 public function testRegexContainment()
 {
     $this->assertTrue(Validator::isIp('127.0.0.1', null, array('contains' => false)));
     $this->expectException('/Unknown modifier/');
     $this->assertFalse(Validator::isIp('127.0.0.1', null, array('contains' => true)));
     Validator::add('foo', '/foo/', array('contains' => true));
     $this->assertTrue(Validator::isFoo('foobar'));
     Validator::add('foo', 'foo', array('contains' => false));
     $this->assertFalse(Validator::isFoo('foobar'));
     $this->assertTrue(Validator::isFoo('foo'));
 }
Beispiel #16
0
 public function testValidationWithContextData()
 {
     Validator::add('someModelRule', function ($value, $format, $options) {
         return $value === 'Title' && $options['values']['body'] === 'Body';
     });
     $result = Validator::check(array('title' => 'Title', 'body' => 'Body'), array('title' => array('someModelRule')));
     $this->assertIdentical(array(), $result);
     $result = Validator::check(array('title' => 'Title', 'body' => 'Not Body'), array('title' => array('someModelRule')));
     $this->assertIdentical(array('title' => array(0)), $result);
 }
Beispiel #17
0
 public static function __init()
 {
     /*
      * Some special validation rules
      */
     Validator::add('uniqueEmail', function ($value) {
         $current_user = Auth::check('li3b_user');
         if (!empty($current_user)) {
             $user = User::find('first', array('fields' => array('_id'), 'conditions' => array('email' => $value, '_id' => array('$ne' => new MongoId($current_user['_id'])))));
         } else {
             $user = User::find('first', array('fields' => array('_id'), 'conditions' => array('email' => $value)));
         }
         if (!empty($user)) {
             return false;
         }
         return true;
     });
     Validator::add('notEmptyHash', function ($value) {
         if ($value == Password::hash('')) {
             return false;
         }
         return true;
     });
     Validator::add('moreThanFive', function ($value) {
         if (strlen($value) < 5) {
             return false;
         }
         return true;
     });
     Validator::add('notTooLarge', function ($value) {
         if ($value == 'TOO_LARGE.jpg') {
             return false;
         }
         return true;
     });
     Validator::add('invalidFileType', function ($value) {
         if ($value == 'INVALID_FILE_TYPE.jpg') {
             return false;
         }
         return true;
     });
     parent::__init();
     /*
      * If told to ues a specific connection, do so.
      * Otherwise, use the default li3b_users connection.
      * Note: This model requires MongoDB.
      * Also note: This must be called AFTER parent::__init()
      *
      * This is useful if the main application also uses MongoDB
      * and wishes everything to use the same database...Be it
      * local or on something like MongoLab or wherever.
      *
      * In fact, when gluing together libraries, one may choose
      * all libraries that use the same database and kinda go
      * with each other. That way it'll end up looking like a single
      * cohesive application from the database's point of view.
      * Of course the it's difficult to avoid conflicts in the MongoDB
      * collection names. In this case, this model is prefixing the
      * library name to the collection in order to ensure there are
      * no conflicts.
      */
     $libConfig = Libraries::get('li3b_users');
     $connection = isset($libConfig['useConnection']) ? $libConfig['useConnection'] : 'li3b_users';
     static::meta('connection', $connection);
 }
Beispiel #18
0
<?php

namespace app\models;

use lithium\util\Validator;
use lithium\util\String;
class Documents extends \lithium\data\Model
{
    protected $_meta = array('connection' => 'default_kyc');
    public $validates = array('email' => array(array('uniqueEmail', 'message' => 'This Email is already used'), array('notEmpty', 'message' => 'Please enter your email address'), array('email', 'message' => 'Not a valid email address')));
}
Validator::add('uniqueEmail', function ($value, $rule, $options) {
    $conflicts = Users::count(array('email' => $value));
    if ($conflicts) {
        return false;
    }
    return true;
});
Beispiel #19
0
/**
 * Integration with `View`. Embeds message translation aliases into the `View`
 * class (or other content handler, if specified) when content is rendered. This
 * enables translation functions, i.e. `<?=$t("Translated content"); ?>`.
 */
Media::applyFilter('_handle', function ($self, $params, $chain) {
    $params['handler'] += array('outputFilters' => array());
    $params['handler']['outputFilters'] += Message::aliases();
    return $chain->next($self, $params, $chain);
});
/**
 * Integration with `Validator`. You can load locale dependent rules into the `Validator`
 * by specifying them manually or retrieving them with the `Catalog` class.
 */
foreach (array('phone', 'postalCode', 'ssn') as $name) {
    Validator::add($name, Catalog::read(true, "validation.{$name}", 'en_US'));
}
/**
 * Intercepts dispatching processes in order to set the effective locale by using
 * the locale of the request or if that is not available retrieving a locale preferred
 * by the client.
 */
ActionDispatcher::applyFilter('_callable', function ($self, $params, $chain) {
    $request = $params['request'];
    $controller = $chain->next($self, $params, $chain);
    if (!$request->locale) {
        $request->params['locale'] = Locale::preferred($request);
    }
    Environment::set(Environment::get(), array('locale' => $request->locale));
    return $controller;
});
Beispiel #20
0
	public static function __init() {
		$class =  __CLASS__;
		/**
		 * ROLES
		 * Note: You don't need to use Minerva's role based access system.
		 * It's a very lightweight system designed to provide basic coverage.
		 * Your needs may fall within the scope of it and you can feel free to
		 * create new roles and access rules using the Access class. However, you
		 * may not find it meeting your needs. You can create your own access
		 * system and simply ignore the "role" field on the User model and/or
		 * always set it to "administrator" and use a different field.
		 * If you don't want to use Minerva's basic role system, you'll need to
		 * adjust the access rules for each controller (which can be done in
		 * your library's Page/User/Block model).
		*/
		// Replace user roles
		$class::_object()->_user_roles = static::_object()->_user_roles;
		// Fill form with role options
		$class::_object()->_schema['role']['form']['options'] = User::user_roles();
		
		/*
		 * Some special validation rules
		*/
		Validator::add('uniqueEmail', function($value) {
			$user = User::find('first', array('fields' => array('_id'), 'conditions' => array('email' => $value)));
			if(!empty($user)) {
			    return false;
			}
			return true;
		});
		
		Validator::add('notEmptyHash', function($value) {    
			if($value == 'da39a3ee5e6b4b0d3255bfef95601890afd80709') {	
			    return false;
			}
			return true;
		});
		    
		Validator::add('moreThanFive', function($value) {
			if(strlen($value) < 5) {	
			    return false;
			}
			return true;
		});
		
		parent::__init();
	}