Skip to content

Instantly share code, notes, and snippets.

@sunvisor
Created March 12, 2019 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunvisor/53657d32bee8af0b94e1896b342eb1db to your computer and use it in GitHub Desktop.
Save sunvisor/53657d32bee8af0b94e1896b342eb1db to your computer and use it in GitHub Desktop.
Symfony のバリデーションの使用法

Symfony のバリデーションの使用法

https://symfony.com/doc/current/validation.html

validator サービス

  • Entity に値をセットして validate メソッドを呼ぶとエラーのリストが帰る
  • エラーのリストは ConstraintViolationList オブジェクト
  • string にキャストすることができる
<?php
    $entity = new SomeEntity();
    $entity->setFoo('bar');
    $validator = $this->get('validator');
    $errors = $validator->validate($entity);

    if ($count($errors)) {
        return (string) $errors;
    }

設定

  • app/config/config.yml の framework セクションに次の記述を追加。アノテーションで記述する前提
    validation: { enable_annotations: true }

アノテーションの書き方

アノテーションを使う Entity で use 文を書く

<?php
use Symfony\Component\Validator\Constraints as Assert;
  • 必須項目
<?php
/**
 * @Assert\NotBlank(message="is required")
 */
  • 長さ制限
<?php
/**
 * @Assert\Length(
 *    min = 3,
 *    max = 50,
 *    minMessage = "は {{ limit }} 文字以上必要です"
 *    maxMessage = "は {{ limit }} 文字までです"
 * )
 */

結果の取り出し

  • getPropertyPath でフィールド名が取得できる
  • getMessage
<?php
        if (count($errors) > 0) {
            $messages = [];
            foreach ($errors as $error) {
                $messages[] = $error->getPropertyPath() . ' ' . $error->getMessage();
            }
            $this->validationMessage = implode('<br />', $messages);
            return false;
        }

#symfony #doctrine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment