2016-09-01 7 views
1

2組の入力フィールドのうち、どちらか一方のみが必要です。私は検証の権利を得ることができません。Yii2検証時

listing_image_urlおよびposter_image_urlは、$model->listingImageがnullの場合にのみ必要です。

strlen($model->listingImage) == 0も試しました。

 [['listing_image_url', 'poster_image_url'], 'required', 
      'when' => function($model){ 

       var_dump($model->listingImage); //result is empty string '0' 

       return $model->listingImage == NULL && $model->posterImage == NULL; 
      },'whenClient' => "function(attribute, value) { 
        return $('#vod-listingimage').val() == '' && $('#vod-posterimage').val() == ''; 
      }", 'message' => 'look' 
     ], 

ちょうど上記と同じですが、逆です。

[['listingImage', 'posterImage'], 'required', 
       'when' => function($model) { 
        return $model->listing_image_url == NULL && $model->poster_image_url == NULL; 
       }, 
       'whenClient' => "function(attribute, value) { 

        return $('#vod-listing_image_url').val() == '' && $('#vod-poster_image_url').val() == ''; 
       }", 'message' => 'hi' 
      ], 
+0

あなたは[真理値表](https://en.wikipedia.org/wiki/Truth_table)を使用して、おそらくあなたのルールを明確にもらえますか? 'poster_image'と' listing_image_url'を有効に設定していますか? – topher

答えて

1

あなたはこのように、バックエンド側のモデルの検証のためにinline validator独自に作成することができます。

[['listingImage', 'posterImage'], function($attribute, $params) { 
    if ($this->listingImage === null && empty($this->$attribute)) { 
      $this->addError($attribute, 'Can not be blank if listingImage is null'); 
    } 
}] 

また、カスタムstandalone validatorを構築することができ、クライアント側の検証を提供するために。

0

私は自分自身に何か似たように試みましたが、その動作は実際には奇妙です。 しかし、2つのフィールドのうち1つだけが選択されているかどうかを確認するバリデーターを作成することができます。

public function validateListingAgainstPoster($attribute, $params) 
{ 
    if (!empty($this->listing_image_url) && !empty($this->poster_image_url)) { 
     $this->addError($attribute, 'Only one of "Listing" or "Poster" fields can be selected.'); 
    } 
    if (empty($this->listing_image_url) && empty($this->poster_image_url)) { 
     $this->addError($attribute, 'Please select one of "Listing" or "Poster Group".'); 
    } 
} 

そして、あなたのルールで:

[['listing_image_url', 'poster_image_url'], 'validateListingAgainstPoster', 'skipOnEmpty' => false, 'skipOnError' => false], 
+0

私は実際にそれを働かせました。 @ nadarの答えを見て、私は '===' NULLを追加しました。それは問題を修正したようです。もう少しテストをして戻ってきます。 – Ciprian

+0

ああ、これは素晴らしいことだ!私はempty()を使って試していました。あなたがこれを管理するなら、あなたの答えを投稿してください。 –

関連する問題