2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複数フィールドのvalidation

Posted at

※ symfony1.4を対象にしています

複数フィールドのvalidation

特定のフィールドに値が入っている時のみ、他の特定フィールドにvalidationをかけたいときがある
symfony1.4のドキュメントを見ると
http://symfony.com/legacy/doc/forms/1_4/ja/02-form-validation
にグローバルバリデータとして紹介されている

用意されているクラスは
http://www.symfony-project.org/api/1_4/sfValidatorSchema#method_setpostvalidator
こちらにのっているものだけで、その他の場合は自分で実装する形になる

実装方法

PostValidatorを利用する

PreValidatorもあるらしい、けどPostValidatorを推奨している

formクラスのsetupメソッド内で

$this->validatorSchema->setPostValidator(
  new sfValidatorCallback(
    array('callback' => array($this, 'postValidatorMethod'))
    array('invalid' => 'エラーメッセージ')
  )
);

とする
callbackメソッド(postValidatorMethod)を定義する

public function postValidatorMethod($validator, $values)
{
  // ここでの$valuesはvalidation済フォームデータ
  if ($values['特定のフィールド1'] !== '') {
    // $values['特定のフィールド2']をチェックするとか
  }
}

postValidatorとsfValidatorCallbackを利用すると、フォーム全体のデータを使って自由にvalidationをかけることができる
postValidator(グローバルバリデータ)を使ってvalidationエラーが発生した場合、エラー内容はgetGlobalErrors()で取得できる

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?