yii\validators\Validator::createValidator PHP Method

createValidator() public static method

Creates a validator object.
public static createValidator ( string | Closure $type, Model $model, array | string $attributes, array $params = [] ) : Validator
$type string | Closure the validator type. This can be either: * a built-in validator name listed in [[builtInValidators]]; * a method name of the model class; * an anonymous function; * a validator class name.
$model yii\base\Model the data model to be validated.
$attributes array | string list of attributes to be validated. This can be either an array of the attribute names or a string of comma-separated attribute names.
$params array initial values to be applied to the validator properties.
return Validator the validator
    public static function createValidator($type, $model, $attributes, $params = [])
    {
        $params['attributes'] = $attributes;
        if ($type instanceof \Closure || $model->hasMethod($type)) {
            // method-based validator
            $params['class'] = __NAMESPACE__ . '\\InlineValidator';
            $params['method'] = $type;
        } else {
            if (isset(static::$builtInValidators[$type])) {
                $type = static::$builtInValidators[$type];
            }
            if (is_array($type)) {
                $params = array_merge($type, $params);
            } else {
                $params['class'] = $type;
            }
        }
        return Yii::createObject($params);
    }

Usage Example

Beispiel #1
1
 public function validateEndpoint()
 {
     $url = $this->baseUrl . $this->endpoint;
     $validator = Validator::createValidator('url', $this, []);
     if ($validator->validate($url, $error)) {
         // Crop fragment
         if (($pos = strpos($this->endpoint, '#')) !== false) {
             $this->endpoint = substr($this->endpoint, 0, $pos);
         }
         // Crop query
         if (($pos = strpos($this->endpoint, '?')) !== false) {
             $this->endpoint = substr($this->endpoint, 0, $pos);
         }
         // Parse params
         $query = parse_url($url, PHP_URL_QUERY);
         if (trim($query) !== '') {
             foreach (explode('&', $query) as $couple) {
                 list($key, $value) = explode('=', $couple, 2) + [1 => ''];
                 $this->queryKeys[] = urldecode($key);
                 $this->queryValues[] = urldecode($value);
                 $this->queryActives[] = true;
             }
         }
     } else {
         $this->addError('endpoint', $error);
     }
 }
All Usage Examples Of yii\validators\Validator::createValidator