0 フォロワー

クラス yii\validators\CompareValidator

継承yii\validators\CompareValidator » yii\validators\Validator » yii\base\Component » yii\base\BaseObject
実装yii\base\Configurable
利用可能なバージョン2.0
ソースコード https://github.com/yiisoft/yii2/blob/master/framework/validators/CompareValidator.php

CompareValidator は、指定された属性値を別の値と比較します。

比較対象の値は、別の属性値($compareAttribute を介して指定)または定数($compareValue を介して指定)にすることができます。両方が指定されている場合、後者が優先されます。どちらも指定されていない場合、属性はソース属性名に "_repeat" を追加した名前を持つ別の属性と比較されます。

CompareValidator は、$operator プロパティを介して指定された、さまざまな比較演算子をサポートしています。

デフォルトの比較関数は文字列値に基づいており、値はバイト単位で比較されます。数値を比較する場合は、数値比較を有効にするために $typeTYPE_NUMBER に設定してください。

公開プロパティ

継承されたプロパティを非表示

プロパティ 説明 定義元
$attributeNames array 属性名。 yii\validators\Validator
$attributes array|string このバリデーターによって検証される属性。 yii\validators\Validator
$behaviors yii\base\Behavior[] このコンポーネントにアタッチされたビヘイビアのリスト。 yii\base\Component
$builtInValidators array ビルトインバリデーターのリスト (name => class または設定) yii\validators\Validator
$compareAttribute string 比較対象となる属性名。 yii\validators\CompareValidator
$compareValue mixed 比較対象となる定数値。 yii\validators\CompareValidator
$enableClientValidation boolean このバリデーターのクライアントサイド検証を有効にするかどうか。 yii\validators\Validator
$except array|string バリデーターを適用しないシナリオ。 yii\validators\Validator
$isEmpty callable|null isEmpty() のデフォルト実装を置き換える PHP callable。 yii\validators\Validator
$message string ユーザー定義のエラーメッセージ。 yii\validators\CompareValidator
$on array|string バリデーターを適用できるシナリオ。 yii\validators\Validator
$operator string 比較演算子。 yii\validators\CompareValidator
$skipOnEmpty boolean 属性値が null または空文字列の場合、この検証ルールをスキップするかどうか。 yii\validators\Validator
$skipOnError boolean 検証対象の属性に、以前のルールによる検証エラーが既に存在する場合、この検証ルールをスキップするかどうか。 yii\validators\Validator
$type string 比較対象の値の型。 yii\validators\CompareValidator
$validationAttributes array|null 属性名のリスト。 yii\validators\Validator
$when callable|null 戻り値がこのバリデーターを適用するかどうかを決定する PHP callable。 yii\validators\Validator
$whenClient string|null 戻り値がこのバリデーターをクライアントサイドで適用するかどうかを決定する JavaScript 関数名。 yii\validators\Validator

公開メソッド

継承されたメソッドを非表示

メソッド 説明 定義元
__call() クラスメソッドではない名前付きメソッドを呼び出します。 yii\base\Component
__clone() このメソッドは、既存のオブジェクトを複製してオブジェクトが作成された後に呼び出されます。 yii\base\Component
__construct() コンストラクター。 yii\base\BaseObject
__get() コンポーネントプロパティの値を返します。 yii\base\Component
__isset() プロパティが設定されているか(つまり、定義されていて null ではないか)を確認します。 yii\base\Component
__set() コンポーネントプロパティの値を設定します。 yii\base\Component
__unset() コンポーネントプロパティを null に設定します。 yii\base\Component
addError() 指定された属性に関するエラーをモデルオブジェクトに追加します。 yii\validators\Validator
attachBehavior() このコンポーネントにビヘイビアをアタッチします。 yii\base\Component
attachBehaviors() コンポーネントにビヘイビアのリストをアタッチします。 yii\base\Component
behaviors() このコンポーネントが動作するべきビヘイビアのリストを返します。 yii\base\Component
canGetProperty() プロパティを読み取ることができるかどうかを示す値を返します。 yii\base\Component
canSetProperty() プロパティを設定できるかどうかを示す値を返します。 yii\base\Component
className() このクラスの完全修飾名を返します。 yii\base\BaseObject
clientValidateAttribute() クライアントサイドバリデーションを実行するために必要なJavaScriptを返します。 yii\validators\CompareValidator
createValidator() バリデータオブジェクトを作成します。 yii\validators\Validator
detachBehavior() コンポーネントからビヘイビアをデタッチします。 yii\base\Component
detachBehaviors() コンポーネントからすべてのビヘイビアをデタッチします。 yii\base\Component
ensureBehaviors() behaviors()で宣言されたビヘイビアがこのコンポーネントにアタッチされていることを確認します。 yii\base\Component
getAttributeNames() 先頭に!文字のないクリーンな属性名を返します。 yii\validators\Validator
getBehavior() 指定された名前のビヘイビアオブジェクトを返します。 yii\base\Component
getBehaviors() このコンポーネントにアタッチされているすべてのビヘイビアを返します。 yii\base\Component
getClientOptions() クライアントサイドバリデーションのオプションを返します。 yii\validators\CompareValidator
getValidationAttributes() このバリデータが適用される属性のリストを返します。 yii\validators\Validator
hasEventHandlers() 指定されたイベントにハンドラがアタッチされているかどうかを示す値を返します。 yii\base\Component
hasMethod() メソッドが定義されているかどうかを示す値を返します。 yii\base\Component
hasProperty() このコンポーネントにプロパティが定義されているかどうかを示す値を返します。 yii\base\Component
init() オブジェクトを初期化します。 yii\validators\CompareValidator
isActive() 指定されたシナリオと属性に対してバリデータがアクティブかどうかを示す値を返します。 yii\validators\Validator
isEmpty() 指定された値が空かどうかを確認します。 yii\validators\Validator
off() このコンポーネントから既存のイベントハンドラをデタッチします。 yii\base\Component
on() イベントにイベントハンドラをアタッチします。 yii\base\Component
trigger() イベントをトリガーします。 yii\base\Component
validate() 指定された値を検証します。 yii\validators\Validator
validateAttribute() 単一の属性を検証します。 yii\validators\CompareValidator
validateAttributes() 指定されたオブジェクトを検証します。 yii\validators\Validator

保護されたメソッド

継承されたメソッドを非表示

メソッド 説明 定義元
compareValues() 指定された演算子を使用して2つの値を比較します。 yii\validators\CompareValidator
formatMessage() I18Nを使用してメッセージをフォーマットします。\Yii::$appが利用できない場合は、単純なstrtrを使用します。 yii\validators\Validator
validateValue() 値を検証します。 yii\validators\CompareValidator

定数

継承された定数を非表示

定数 説明 定義元
TYPE_NUMBER 'number' 数値による比較$typeを指定するための定数。 yii\validators\CompareValidator
TYPE_STRING 'string' 数値による比較$typeを指定するための定数。 yii\validators\CompareValidator

プロパティの詳細

継承されたプロパティを非表示

$compareAttribute public property

比較対象となる属性の名前です。このプロパティと$compareValueの両方が設定されている場合、後者が優先されます。どちらも設定されていない場合は、検証対象の属性名に'_repeat'を付加した名前の別の属性と比較すると想定されます。たとえば、'password'が検証対象の場合、比較対象となる属性は'password_repeat'になります。

$compareValueも参照してください。

public string $compareAttribute null
$compareValue public property

比較対象となる定数値です。このプロパティと$compareAttributeの両方が設定されている場合、このプロパティが優先されます。

$compareAttributeも参照してください。

public mixed $compareValue null
$message public property

ユーザー定義のエラーメッセージです。以下のプレースホルダーを含めることができ、バリデータによって適切に置き換えられます。

  • {attribute}: 検証対象の属性のラベル
  • {value}: 検証対象の属性の値
  • {compareValue}: 比較対象の値または属性ラベル
  • {compareAttribute}: 比較対象の属性のラベル
  • {compareValueOrAttribute}: 比較対象の値または属性ラベル
public string $message null
$operator public property

比較演算子です。以下の演算子がサポートされています。

  • ==: 2つの値が等しいかどうかをチェックします。比較は非厳密モードで行われます。
  • ===: 2つの値が等しいかどうかをチェックします。比較は厳密モードで行われます。
  • !=: 2つの値が等しくないかどうかをチェックします。比較は非厳密モードで行われます。
  • !==: 2つの値が等しくないかどうかをチェックします。比較は厳密モードで行われます。
  • >: 検証対象の値が比較対象の値よりも大きいかどうかをチェックします。
  • >=: 検証対象の値が比較対象の値以上かどうかをチェックします。
  • <: 検証対象の値が比較対象の値よりも小さいかどうかをチェックします。
  • <=: 検証対象の値が比較対象の値以下かどうかをチェックします。

数値を比較する場合は、$typenumberに設定してください。

public string $operator '=='
$type public property

比較される値の型です。以下の型がサポートされています。

  • string: 値は文字列として比較されます。比較前に変換は行われません。
  • number: 値は数値として比較されます。文字列値は比較前に数値に変換されます。
public string $type self::TYPE_STRING

メソッドの詳細

継承されたメソッドを非表示

__call() public method

定義先: yii\base\Component::__call()

クラスメソッドではない名前付きメソッドを呼び出します。

このメソッドは、アタッチされているビヘイビアに指定された名前のメソッドがあるかどうかをチェックし、利用可能な場合は実行します。

これはPHPのマジックメソッドであり、未知のメソッドが呼び出されたときに暗黙的に呼び出されるため、直接呼び出さないでください。

public mixed __call ( $name, $params )
$name string

メソッド名

$params array

メソッドパラメータ

戻り値 mixed

メソッドの戻り値

例外 yii\base\UnknownMethodException

未知のメソッドを呼び出した場合

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__clone() public method

定義先: yii\base\Component::__clone()

このメソッドは、既存のオブジェクトを複製してオブジェクトが作成された後に呼び出されます。

古いオブジェクトにアタッチされているため、すべてのビヘイビアを削除します。

public void __clone ( )

                public function __clone()
{
    $this->_events = [];
    $this->_eventWildcards = [];
    $this->_behaviors = null;
}

            
__construct() public メソッド

定義場所: yii\base\BaseObject::__construct()

コンストラクター。

デフォルトの実装では、次の2つの処理を行います。

  • 指定された設定$configを使用してオブジェクトを初期化します。
  • init() を呼び出します。

このメソッドを子クラスでオーバーライドする場合は、

  • コンストラクタの最後の引数を、ここにある$configのような設定配列にすることをお勧めします。
  • コンストラクタの最後に、親の実装を呼び出してください。
public void __construct ( $config = [] )
$config array

オブジェクトのプロパティを初期化するために使用される、名前と値のペア

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public メソッド

定義場所: yii\base\Component::__get()

コンポーネントプロパティの値を返します。

このメソッドは、次の順序でチェックを行い、それに応じて動作します。

  • ゲッターで定義されたプロパティ: ゲッターの結果を返します。
  • ビヘイビアのプロパティ: ビヘイビアのプロパティ値を返します。

これはPHPのマジックメソッドであり、$value = $component->property;を実行した際に暗黙的に呼び出されるため、直接呼び出さないでください。

__set() も参照してください。

public mixed __get ( $name )
$name string

プロパティ名

戻り値 mixed

プロパティ値、またはビヘイビアのプロパティの値

例外 yii\base\UnknownPropertyException

プロパティが定義されていない場合

例外 yii\base\InvalidCallException

プロパティが書き込み専用の場合。

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        // read property, e.g. getName()
        return $this->$getter();
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }
    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public メソッド

定義場所: yii\base\Component::__isset()

プロパティが設定されているか(つまり、定義されていて null ではないか)を確認します。

このメソッドは、次の順序でチェックを行い、それに応じて動作します。

  • セッターで定義されたプロパティ: プロパティが設定されているかどうかを返します。
  • ビヘイビアのプロパティ: プロパティが設定されているかどうかを返します。
  • 存在しないプロパティの場合はfalseを返します。

これはPHPのマジックメソッドであり、isset($component->property)を実行した際に暗黙的に呼び出されるため、直接呼び出さないでください。

https://www.php.net/manual/en/function.isset.php も参照してください。

public boolean __isset ( $name )
$name string

プロパティ名またはイベント名

戻り値 boolean

指定されたプロパティが設定されているかどうか

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name !== null;
        }
    }
    return false;
}

            
__set() public メソッド

定義場所: yii\base\Component::__set()

コンポーネントプロパティの値を設定します。

このメソッドは、次の順序でチェックを行い、それに応じて動作します。

  • セッターで定義されたプロパティ: プロパティ値を設定します。
  • "on xyz"形式のイベント: "xyz"イベントにハンドラーをアタッチします。
  • "as xyz"形式のビヘイビア: "xyz"という名前のビヘイビアをアタッチします。
  • ビヘイビアのプロパティ: ビヘイビアのプロパティ値を設定します。

これはPHPのマジックメソッドであり、$component->property = $value;を実行した際に暗黙的に呼び出されるため、直接呼び出さないでください。

__get() も参照してください。

public void __set ( $name, $value )
$name string

プロパティ名またはイベント名

$value mixed

プロパティ値

例外 yii\base\UnknownPropertyException

プロパティが定義されていない場合

例外 yii\base\InvalidCallException

プロパティが読み取り専用の場合。

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        // set property
        $this->$setter($value);
        return;
    } elseif (strncmp($name, 'on ', 3) === 0) {
        // on event: attach event handler
        $this->on(trim(substr($name, 3)), $value);
        return;
    } elseif (strncmp($name, 'as ', 3) === 0) {
        // as behavior: attach behavior
        $name = trim(substr($name, 3));
        $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = $value;
            return;
        }
    }
    if (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}

            
__unset() public メソッド

定義場所: yii\base\Component::__unset()

コンポーネントプロパティを null に設定します。

このメソッドは、次の順序でチェックを行い、それに応じて動作します。

  • セッターで定義されたプロパティ: プロパティ値をnullに設定します。
  • ビヘイビアのプロパティ: プロパティ値をnullに設定します。

これはPHPのマジックメソッドであり、unset($component->property)を実行した際に暗黙的に呼び出されるため、直接呼び出さないでください。

https://www.php.net/manual/en/function.unset.php も参照してください。

public void __unset ( $name )
$name string

プロパティ名

例外 yii\base\InvalidCallException

プロパティが読み取り専用の場合。

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = null;
            return;
        }
    }
    throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}

            
addError() public メソッド

定義場所: yii\validators\Validator::addError()

指定された属性に関するエラーをモデルオブジェクトに追加します。

これは、メッセージの選択と国際化を行うヘルパーメソッドです。

public void addError ( $model, $attribute, $message, $params = [] )
$model yii\base\Model

検証対象のデータモデル

$attribute string

検証対象の属性

$message string

エラーメッセージ

$params array

エラーメッセージ内のプレースホルダーの値

                public function addError($model, $attribute, $message, $params = [])
{
    $params['attribute'] = $model->getAttributeLabel($attribute);
    if (!isset($params['value'])) {
        $value = $model->$attribute;
        if (is_array($value)) {
            $params['value'] = 'array()';
        } elseif (is_object($value) && !method_exists($value, '__toString')) {
            $params['value'] = '(object)';
        } else {
            $params['value'] = $value;
        }
    }
    $model->addError($attribute, $this->formatMessage($message, $params));
}

            
attachBehavior() public メソッド

定義場所: yii\base\Component::attachBehavior()

このコンポーネントにビヘイビアをアタッチします。

このメソッドは、指定された設定に基づいてビヘイビアオブジェクトを作成します。その後、yii\base\Behavior::attach() メソッドを呼び出すことで、ビヘイビアオブジェクトがこのコンポーネントにアタッチされます。

detachBehavior() も参照してください。

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name string

ビヘイビアの名前。

$behavior string|array|yii\base\Behavior

ビヘイビアの設定。次のいずれかになります。

  • yii\base\Behavior オブジェクト
  • ビヘイビアクラスを指定する文字列
  • ビヘイビアオブジェクトの作成にYii::createObject() に渡されるオブジェクト設定配列。
戻り値 yii\base\Behavior

ビヘイビアオブジェクト

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
attachBehaviors() public メソッド

定義場所: yii\base\Component::attachBehaviors()

コンポーネントにビヘイビアのリストをアタッチします。

各ビヘイビアは、その名前でインデックス付けされ、yii\base\Behavior オブジェクト、ビヘイビアクラスを指定する文字列、またはビヘイビアを作成するための設定配列である必要があります。

attachBehavior() も参照してください。

public void attachBehaviors ( $behaviors )
$behaviors array

コンポーネントにアタッチされるビヘイビアのリスト

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            
behaviors() public メソッド

定義場所: yii\base\Component::behaviors()

このコンポーネントが動作するべきビヘイビアのリストを返します。

子クラスはこのメソッドをオーバーライドして、ビヘイビアとして動作させたいビヘイビアを指定できます。

このメソッドの戻り値は、ビヘイビア名でインデックス付けされたビヘイビアオブジェクトまたは設定の配列である必要があります。ビヘイビアの設定は、ビヘイビアクラスを指定する文字列、または次の構造の配列のいずれかです。

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

ビヘイビアクラスはyii\base\Behaviorを継承する必要があることに注意してください。ビヘイビアは名前付きまたは匿名でアタッチできます。配列キーとして名前を使用する場合、この名前を使用して、後でgetBehavior()を使用してビヘイビアを取得したり、detachBehavior()を使用してビヘイビアをデタッチしたりできます。匿名ビヘイビアは取得またはデタッチできません。

このメソッドで宣言されたビヘイビアは、(オンデマンドで)自動的にコンポーネントにアタッチされます。

public array behaviors ( )
戻り値 array

ビヘイビアの設定。

                public function behaviors()
{
    return [];
}

            
canGetProperty() publicメソッド

定義場所: yii\base\Component::canGetProperty()

プロパティを読み取ることができるかどうかを示す値を返します。

プロパティは、以下の場合に読み取り可能です。

  • クラスが指定された名前に関連付けられたゲッターメソッドを持つ場合(この場合、プロパティ名は大小文字を区別しません)。
  • クラスが指定された名前のメンバ変数を持つ場合($checkVarsがtrueの場合)。
  • アタッチされたビヘイビアが、指定された名前の読み取り可能なプロパティを持つ場合($checkBehaviorsがtrueの場合)。

参照: canSetProperty().

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

プロパティ名

$checkVars boolean

メンバ変数をプロパティとして扱うかどうか

$checkBehaviors boolean

ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか

戻り値 boolean

プロパティが読み取り可能かどうか

                public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
canSetProperty() publicメソッド

定義場所: yii\base\Component::canSetProperty()

プロパティを設定できるかどうかを示す値を返します。

プロパティは、以下の場合に書き込み可能です。

  • クラスが指定された名前に関連付けられたセッターメソッドを持つ場合(この場合、プロパティ名は大小文字を区別しません)。
  • クラスが指定された名前のメンバ変数を持つ場合($checkVarsがtrueの場合)。
  • アタッチされたビヘイビアが、指定された名前の書き込み可能なプロパティを持つ場合($checkBehaviorsがtrueの場合)。

参照: canGetProperty().

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

プロパティ名

$checkVars boolean

メンバ変数をプロパティとして扱うかどうか

$checkBehaviors boolean

ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか

戻り値 boolean

プロパティが書き込み可能かどうか

                public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
className() public staticメソッド
2.0.14より非推奨。PHP 5.5以降では、代わりに::classを使用してください。

定義場所: yii\base\BaseObject::className()

このクラスの完全修飾名を返します。

public static string className ( )
戻り値 string

このクラスの完全修飾名。

                public static function className()
{
    return get_called_class();
}

            
clientValidateAttribute() publicメソッド

クライアントサイドバリデーションを実行するために必要なJavaScriptを返します。

getClientOptions() を呼び出して、クライアントサイド検証のためのオプション配列を生成します。

バリデータがクライアントサイド検証をサポートできる場合、JavaScript検証コードを返すようにこのメソッドをオーバーライドできます。

以下のJavaScript変数は事前に定義されており、検証コードで使用できます。

  • attribute: 検証対象の属性を記述するオブジェクト。
  • value: 検証対象の値。
  • messages: 属性の検証エラーメッセージを保持するために使用される配列。
  • deferred: 非同期検証のための遅延オブジェクトを保持するために使用される配列。
  • $form: フォーム要素を含むjQueryオブジェクト。

attributeオブジェクトには、以下のプロパティが含まれています。

  • id: フォーム内の属性を一意に識別するID(例: "loginform-username")。
  • name: 属性名または式(例: 表形式入力の場合は "[0]content")。
  • container: 入力フィールドのコンテナのjQueryセレクタ。
  • input: フォームのコンテキストでの入力フィールドのjQueryセレクタ。
  • error: コンテナのコンテキストでのエラータグのjQueryセレクタ。
  • status: 入力フィールドの状態、0: 空、未入力、1: 検証済み、2: 検証待ち、3: 検証中。
public string|null clientValidateAttribute ( $model, $attribute, $view )
$model yii\base\Model

検証対象のデータモデル

$attribute string

検証対象の属性名。

$view yii\web\View

このバリデータが適用されたモデルフォームを含むビューまたはビューファイルのレンダリングに使用されるビューオブジェクト。

戻り値 string|null

クライアントサイド検証スクリプト。バリデータがクライアントサイド検証をサポートしていない場合はNull。

                public function clientValidateAttribute($model, $attribute, $view)
{
    if ($this->compareValue != null && $this->compareValue instanceof \Closure) {
        $this->compareValue = call_user_func($this->compareValue);
    }
    ValidationAsset::register($view);
    $options = $this->getClientOptions($model, $attribute);
    return 'yii.validation.compare(value, messages, ' . Json::htmlEncode($options) . ', $form);';
}

            
compareValues() protectedメソッド

指定された演算子を使用して2つの値を比較します。

protected boolean compareValues ( $operator, $type, $value, $compareValue )
$operator string

比較演算子

$type string

比較対象の値の型

$value mixed

比較対象の値

$compareValue mixed

比較対象の別の値

戻り値 boolean

指定された演算子を使用した比較がtrueかどうか。

                protected function compareValues($operator, $type, $value, $compareValue)
{
    if ($type === self::TYPE_NUMBER) {
        $value = (float) $value;
        $compareValue = (float) $compareValue;
    } else {
        $value = (string) $value;
        $compareValue = (string) $compareValue;
    }
    switch ($operator) {
        case '==':
            return $value == $compareValue;
        case '===':
            return $value === $compareValue;
        case '!=':
            return $value != $compareValue;
        case '!==':
            return $value !== $compareValue;
        case '>':
            return $value > $compareValue;
        case '>=':
            return $value >= $compareValue;
        case '<':
            return $value < $compareValue;
        case '<=':
            return $value <= $compareValue;
        default:
            return false;
    }
}

            
createValidator() public staticメソッド

定義場所: yii\validators\Validator::createValidator()

バリデータオブジェクトを作成します。

public static yii\validators\Validator createValidator ( $type, $model, $attributes, $params = [] )
$type string|Closure

バリデータの型。以下のいずれかです。

  • $builtInValidatorsにリストされている組み込みバリデータ名。
  • モデルクラスのメソッド名。
  • 無名関数。
  • バリデータのクラス名。
$model yii\base\Model

検証対象のデータモデル。

$attributes array|string

検証対象の属性のリスト。属性名の配列、またはカンマ区切りの属性名の文字列のいずれかです。

$params array

バリデータのプロパティに適用される初期値。

戻り値 yii\validators\Validator

バリデータ

                public static function createValidator($type, $model, $attributes, $params = [])
{
    $params['attributes'] = $attributes;
    if ($type instanceof \Closure) {
        $params['class'] = __NAMESPACE__ . '\InlineValidator';
        $params['method'] = $type;
    } elseif (!isset(static::$builtInValidators[$type]) && $model->hasMethod($type)) {
        // method-based validator
        $params['class'] = __NAMESPACE__ . '\InlineValidator';
        $params['method'] = [$model, $type];
    } else {
        unset($params['current']);
        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);
}

            
detachBehavior() publicメソッド

定義場所: yii\base\Component::detachBehavior()

コンポーネントからビヘイビアをデタッチします。

ビヘイビアのyii\base\Behavior::detach()メソッドが呼び出されます。

public yii\base\Behavior|null detachBehavior ( $name )
$name string

ビヘイビアの名前。

戻り値 yii\base\Behavior|null

デタッチされたビヘイビア。ビヘイビアが存在しない場合はNull。

                public function detachBehavior($name)
{
    $this->ensureBehaviors();
    if (isset($this->_behaviors[$name])) {
        $behavior = $this->_behaviors[$name];
        unset($this->_behaviors[$name]);
        $behavior->detach();
        return $behavior;
    }
    return null;
}

            
detachBehaviors() publicメソッド

定義場所: yii\base\Component::detachBehaviors()

コンポーネントからすべてのビヘイビアをデタッチします。

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
ensureBehaviors() publicメソッド

定義位置: yii\base\Component::ensureBehaviors()

behaviors()で宣言されたビヘイビアがこのコンポーネントにアタッチされていることを確認します。

public void ensureBehaviors ( )

                public function ensureBehaviors()
{
    if ($this->_behaviors === null) {
        $this->_behaviors = [];
        foreach ($this->behaviors() as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }
}

            
formatMessage() protectedメソッド (バージョン2.0.12から利用可能)

定義位置: yii\validators\Validator::formatMessage()

I18Nを使用してメッセージをフォーマットします。\Yii::$appが利用できない場合は、単純なstrtrを使用します。

protected string formatMessage ( $message, $params )
$message string
$params array

                protected function formatMessage($message, $params)
{
    if (Yii::$app !== null) {
        return \Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
    }
    $placeholders = [];
    foreach ((array) $params as $name => $value) {
        $placeholders['{' . $name . '}'] = $value;
    }
    return ($placeholders === []) ? $message : strtr($message, $placeholders);
}

            
getAttributeNames() publicメソッド (バージョン2.0.12から利用可能)

定義位置: yii\validators\Validator::getAttributeNames()

先頭に!文字のないクリーンな属性名を返します。

public array getAttributeNames ( )
戻り値 array

属性名。

                public function getAttributeNames()
{
    return array_map(function ($attribute) {
        return ltrim($attribute, '!');
    }, $this->attributes);
}

            
getBehavior() publicメソッド

定義位置: yii\base\Component::getBehavior()

指定された名前のビヘイビアオブジェクトを返します。

public yii\base\Behavior|null getBehavior ( $name )
$name string

ビヘイビア名

戻り値 yii\base\Behavior|null

ビヘイビアオブジェクト、またはビヘイビアが存在しない場合はnull

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            
getBehaviors() publicメソッド

定義位置: yii\base\Component::getBehaviors()

このコンポーネントにアタッチされているすべてのビヘイビアを返します。

public yii\base\Behavior[] getBehaviors ( )
戻り値 yii\base\Behavior[]

このコンポーネントにアタッチされているビヘイビアのリスト

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
getClientOptions() publicメソッド (バージョン2.0.11から利用可能)

クライアントサイドバリデーションのオプションを返します。

このメソッドは通常、clientValidateAttribute()から呼び出されます。クライアントサイド検証に渡されるオプションを変更するために、このメソッドをオーバーライドできます。

public array getClientOptions ( $model, $attribute )
$model yii\base\Model

検証対象のモデル

$attribute string

検証対象の属性名

戻り値 array

クライアントサイド検証のオプション

                public function getClientOptions($model, $attribute)
{
    $options = [
        'operator' => $this->operator,
        'type' => $this->type,
    ];
    if ($this->compareValue !== null) {
        $options['compareValue'] = $this->compareValue;
        $compareLabel = $compareValue = $compareValueOrAttribute = $this->compareValue;
    } else {
        $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
        $compareValue = $model->getAttributeLabel($compareAttribute);
        $options['compareAttribute'] = Html::getInputId($model, $compareAttribute);
        $options['compareAttributeName'] = Html::getInputName($model, $compareAttribute);
        $compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
    }
    if ($this->skipOnEmpty) {
        $options['skipOnEmpty'] = 1;
    }
    $options['message'] = $this->formatMessage($this->message, [
        'attribute' => $model->getAttributeLabel($attribute),
        'compareAttribute' => $compareLabel,
        'compareValue' => $compareValue,
        'compareValueOrAttribute' => $compareValueOrAttribute,
    ]);
    return $options;
}

            
getValidationAttributes() publicメソッド (バージョン2.0.16から利用可能)

定義位置: yii\validators\Validator::getValidationAttributes()

このバリデータが適用される属性のリストを返します。

public array|null getValidationAttributes ( $attributes null )
$attributes array|string|null

検証対象の属性リスト。

  • これがnullの場合、結果はgetAttributeNames()と等しくなります。
  • これが文字列または配列の場合、getAttributeNames()と指定された属性の共通部分が返されます。
戻り値 array|null

属性名のリスト。

                public function getValidationAttributes($attributes = null)
{
    if ($attributes === null) {
        return $this->getAttributeNames();
    }
    if (is_scalar($attributes)) {
        $attributes = [$attributes];
    }
    $newAttributes = [];
    $attributeNames = $this->getAttributeNames();
    foreach ($attributes as $attribute) {
        // do not strict compare, otherwise int attributes would fail due to to string conversion in getAttributeNames() using ltrim().
        if (in_array($attribute, $attributeNames, false)) {
            $newAttributes[] = $attribute;
        }
    }
    return $newAttributes;
}

            
hasEventHandlers() publicメソッド

定義位置: yii\base\Component::hasEventHandlers()

指定されたイベントにハンドラがアタッチされているかどうかを示す値を返します。

public boolean hasEventHandlers ( $name )
$name string

イベント名

戻り値 boolean

イベントにハンドラがアタッチされているかどうか。

                public function hasEventHandlers($name)
{
    $this->ensureBehaviors();
    if (!empty($this->_events[$name])) {
        return true;
    }
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
            return true;
        }
    }
    return Event::hasHandlers($this, $name);
}

            
hasMethod() publicメソッド

定義位置: yii\base\Component::hasMethod()

メソッドが定義されているかどうかを示す値を返します。

メソッドは、以下の場合に定義済みとみなされます。

  • クラスが指定された名前のメソッドを持つ場合
  • アタッチされたビヘイビアが指定された名前のメソッドを持つ場合($checkBehaviorsがtrueの場合)。
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

プロパティ名

$checkBehaviors boolean

ビヘイビアのメソッドをこのコンポーネントのメソッドとして扱うかどうか

戻り値 boolean

メソッドが定義されているかどうか

                public function hasMethod($name, $checkBehaviors = true)
{
    if (method_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->hasMethod($name)) {
                return true;
            }
        }
    }
    return false;
}

            
hasProperty() publicメソッド

定義位置: yii\base\Component::hasProperty()

このコンポーネントにプロパティが定義されているかどうかを示す値を返します。

プロパティは、以下の場合に定義済みとみなされます。

  • クラスが指定された名前と関連付けられたゲッターまたはセッターメソッドを持つ場合(この場合、プロパティ名はケースインセンシティブです)。
  • クラスが指定された名前のメンバ変数を持つ場合($checkVarsがtrueの場合)。
  • アタッチされたビヘイビアが指定された名前のプロパティを持つ場合($checkBehaviorsがtrueの場合)。

参照

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

プロパティ名

$checkVars boolean

メンバ変数をプロパティとして扱うかどうか

$checkBehaviors boolean

ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか

戻り値 boolean

プロパティが定義されているかどうか

                public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
    return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}

            
init() public メソッド

オブジェクトを初期化します。

このメソッドは、オブジェクトが指定された設定で初期化された後、コンストラクタの最後に呼び出されます。

public void init ( )

                public function init()
{
    parent::init();
    if ($this->message === null) {
        switch ($this->operator) {
            case '==':
            case '===':
                $this->message = Yii::t('yii', '{attribute} must be equal to "{compareValueOrAttribute}".');
                break;
            case '!=':
            case '!==':
                $this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValueOrAttribute}".');
                break;
            case '>':
                $this->message = Yii::t('yii', '{attribute} must be greater than "{compareValueOrAttribute}".');
                break;
            case '>=':
                $this->message = Yii::t('yii', '{attribute} must be greater than or equal to "{compareValueOrAttribute}".');
                break;
            case '<':
                $this->message = Yii::t('yii', '{attribute} must be less than "{compareValueOrAttribute}".');
                break;
            case '<=':
                $this->message = Yii::t('yii', '{attribute} must be less than or equal to "{compareValueOrAttribute}".');
                break;
            default:
                throw new InvalidConfigException("Unknown operator: {$this->operator}");
        }
    }
}

            
isActive() public メソッド

定義されている場所: yii\validators\Validator::isActive()

指定されたシナリオと属性に対してバリデータがアクティブかどうかを示す値を返します。

バリデータは、以下の場合にアクティブになります。

  • バリデータのonプロパティが空である場合、または
  • バリデータのonプロパティに、指定されたシナリオが含まれている場合
public boolean isActive ( $scenario )
$scenario string

シナリオ名

戻り値 boolean

バリデータが指定されたシナリオに適用されるかどうか。

                public function isActive($scenario)
{
    return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
}

            
isEmpty() public メソッド

定義されている場所: yii\validators\Validator::isEmpty()

指定された値が空かどうかを確認します。

値がnull、空の配列、または空文字列の場合、値は空とみなされます。このメソッドはPHPのempty()とは異なることに注意してください。値が0の場合、falseを返します。

public boolean isEmpty ( $value )
$value mixed

チェックする値

戻り値 boolean

値が空かどうか

                public function isEmpty($value)
{
    if ($this->isEmpty !== null) {
        return call_user_func($this->isEmpty, $value);
    }
    return $value === null || $value === [] || $value === '';
}

            
off() public メソッド

定義されている場所: yii\base\Component::off()

このコンポーネントから既存のイベントハンドラをデタッチします。

このメソッドはon()の逆です。

注:イベント名にワイルドカードパターンが渡された場合、このワイルドカードで登録されたハンドラのみが削除され、このワイルドカードと一致するプレーン名で登録されたハンドラは残ります。

on()も参照してください。

public boolean off ( $name, $handler null )
$name string

イベント名

$handler callable|null

削除するイベントハンドラ。nullの場合、指定されたイベントにアタッチされているすべてのハンドラが削除されます。

戻り値 boolean

ハンドラが見つかり、デタッチされた場合

                public function off($name, $handler = null)
{
    $this->ensureBehaviors();
    if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
        return false;
    }
    if ($handler === null) {
        unset($this->_events[$name], $this->_eventWildcards[$name]);
        return true;
    }
    $removed = false;
    // plain event names
    if (isset($this->_events[$name])) {
        foreach ($this->_events[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_events[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_events[$name] = array_values($this->_events[$name]);
            return true;
        }
    }
    // wildcard event names
    if (isset($this->_eventWildcards[$name])) {
        foreach ($this->_eventWildcards[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_eventWildcards[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
            // remove empty wildcards to save future redundant regex checks:
            if (empty($this->_eventWildcards[$name])) {
                unset($this->_eventWildcards[$name]);
            }
        }
    }
    return $removed;
}

            
on() public メソッド

定義されている場所: yii\base\Component::on()

イベントにイベントハンドラをアタッチします。

イベントハンドラは有効なPHPコールバックである必要があります。いくつかの例を以下に示します。

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

イベントハンドラは、次のシグネチャで定義する必要があります。

function ($event)

ここで、$eventは、イベントに関連付けられたパラメータを含むyii\base\Eventオブジェクトです。

2.0.14以降、イベント名をワイルドカードパターンとして指定できます。

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});

off()も参照してください。

public void on ( $name, $handler, $data null, $append true )
$name string

イベント名

$handler callable

イベントハンドラ

$data mixed

イベントが発生したときにイベントハンドラに渡されるデータ。イベントハンドラが呼び出されると、このデータはyii\base\Event::$dataからアクセスできます。

$append boolean

新しいイベントハンドラを既存のハンドラリストの最後に追加するかどうか。falseの場合、新しいハンドラは既存のハンドラリストの先頭に挿入されます。

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            
trigger() public メソッド

定義されている場所: yii\base\Component::trigger()

イベントをトリガーします。

このメソッドはイベントの発生を表します。クラスレベルのハンドラを含む、イベントにアタッチされたすべてのハンドラを呼び出します。

public void trigger ( $name, yii\base\Event $event null )
$name string

イベント名

$event yii\base\Event|null

イベントインスタンス。設定されていない場合、デフォルトのyii\base\Eventオブジェクトが作成されます。

                public function trigger($name, Event $event = null)
{
    $this->ensureBehaviors();
    $eventHandlers = [];
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (StringHelper::matchWildcard($wildcard, $name)) {
            $eventHandlers[] = $handlers;
        }
    }
    if (!empty($this->_events[$name])) {
        $eventHandlers[] = $this->_events[$name];
    }
    if (!empty($eventHandlers)) {
        $eventHandlers = call_user_func_array('array_merge', $eventHandlers);
        if ($event === null) {
            $event = new Event();
        }
        if ($event->sender === null) {
            $event->sender = $this;
        }
        $event->handled = false;
        $event->name = $name;
        foreach ($eventHandlers as $handler) {
            $event->data = $handler[1];
            call_user_func($handler[0], $event);
            // stop further handling if the event is handled
            if ($event->handled) {
                return;
            }
        }
    }
    // invoke class-level attached handlers
    Event::trigger($this, $name, $event);
}

            
validate() public メソッド

定義されている場所: yii\validators\Validator::validate()

指定された値を検証します。

このメソッドを使用して、データモデルのコンテキスト外で値を検証できます。

public boolean validate ( $value, &$error null )
$value mixed

検証するデータ値。

$error string|null

検証に失敗した場合に返されるエラーメッセージ。

戻り値 boolean

データが有効かどうか。

                public function validate($value, &$error = null)
{
    $result = $this->validateValue($value);
    if (empty($result)) {
        return true;
    }
    list($message, $params) = $result;
    $params['attribute'] = Yii::t('yii', 'the input value');
    if (is_array($value)) {
        $params['value'] = 'array()';
    } elseif (is_object($value)) {
        $params['value'] = 'object';
    } else {
        $params['value'] = $value;
    }
    $error = $this->formatMessage($message, $params);
    return false;
}

            
validateAttribute() public メソッド

単一の属性を検証します。

子クラスは、実際の検証ロジックを提供するためにこのメソッドを実装する必要があります。

public void validateAttribute ( $model, $attribute )
$model yii\base\Model

検証するデータモデル

$attribute string

検証対象の属性名。

                public function validateAttribute($model, $attribute)
{
    $value = $model->$attribute;
    if (is_array($value)) {
        $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
        return;
    }
    if ($this->compareValue !== null) {
        if ($this->compareValue instanceof \Closure) {
            $this->compareValue = call_user_func($this->compareValue);
        }
        $compareLabel = $compareValue = $compareValueOrAttribute = $this->compareValue;
    } else {
        $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
        $compareValue = $model->$compareAttribute;
        $compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
        if (!$this->skipOnError && $model->hasErrors($compareAttribute)) {
            $this->addError(
                $model,
                $attribute,
                Yii::t('yii', '{compareAttribute} is invalid.'),
                ['compareAttribute' => $compareLabel]
            );
            return;
        }
    }
    if (!$this->compareValues($this->operator, $this->type, $value, $compareValue)) {
        $this->addError($model, $attribute, $this->message, [
            'compareAttribute' => $compareLabel,
            'compareValue' => $compareValue,
            'compareValueOrAttribute' => $compareValueOrAttribute,
        ]);
    }
}

            
validateAttributes() public メソッド

定義されている場所: yii\validators\Validator::validateAttributes()

指定されたオブジェクトを検証します。

public void validateAttributes ( $model, $attributes null )
$model yii\base\Model

検証対象のデータモデル

$attributes array|string|null

検証する属性のリスト。属性がバリデータに関連付けられていない場合、無視されます。このパラメータがnullの場合、$attributesにリストされているすべての属性が検証されます。

                public function validateAttributes($model, $attributes = null)
{
    $attributes = $this->getValidationAttributes($attributes);
    foreach ($attributes as $attribute) {
        $skip = $this->skipOnError && $model->hasErrors($attribute)
            || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
        if (!$skip) {
            if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
                $this->validateAttribute($model, $attribute);
            }
        }
    }
}

            
validateValue() protected メソッド

値を検証します。

バリデータクラスは、データモデルのコンテキスト外でのデータ検証をサポートするために、このメソッドを実装できます。

protected array|null validateValue ( $value )
$value mixed

検証するデータ値。

戻り値 array|null

エラーメッセージと、そのエラーメッセージに挿入するパラメータの配列。

return [$this->message, [
    'param1' => $this->param1,
    'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
    'mimeTypes' => implode(', ', $this->mimeTypes),
    'param4' => 'etc...',
]];

}

`php if (!$valid) { ` この例では、message テンプレートは {param1}{formattedLimit}{mimeTypes}{param4} を含むことができます。

データが有効な場合は、Null を返す必要があります。

例外 yii\base\NotSupportedException

バリデータがモデルなしでのデータ検証をサポートしていない場合

                protected function validateValue($value)
{
    if ($this->compareValue === null) {
        throw new InvalidConfigException('CompareValidator::compareValue must be set.');
    }
    if ($this->compareValue instanceof \Closure) {
        $this->compareValue = call_user_func($this->compareValue);
    }
    if (!$this->compareValues($this->operator, $this->type, $value, $this->compareValue)) {
        return [$this->message, [
            'compareAttribute' => $this->compareValue,
            'compareValue' => $this->compareValue,
            'compareValueOrAttribute' => $this->compareValue,
        ]];
    }
    return null;
}