LoginSignup
35
41

More than 5 years have passed since last update.

Laravel Validation メモ

Last updated at Posted at 2016-01-05

Validation Rule をホントによく忘れるのでメモ書き。Laravel5.1で書いてます。

see: https://laravel.com/docs/5.1/validation#available-validation-rules

画像ファイルか確認する

image を使う

PDF ファイルか確認する

mimes:pdf を使う

メールアドレスか確認する

emailを使う

他のフィールドとは別の値にする

例えば、AB とは別の値にする必要がある場合の指定

[
  'A' => 'different:B'
]

Checkbox に値があるか確認する

accepted を使う。 yes/1/trueのいずれかの値であれば良い。

  • HTML側 <input type='checkbox' name='hoge' value='1' />

日付になっているか確認

date を使う。フォーマットが少し変わっている場合などは date_format:format を使う。

ただし、平成N年などは対応していないから、Validationを新しく作る必要あり。

数字3ケタのみ受け付ける。もしくは3ケタ以上4ケタ未満のみ受け付ける。

digits:3 を使い、digits_between:3,4 とする。

DBに存在している値か確認する

exists:table,field を使う。where 句も追加できて、exists:table,field,delete_at,NULLexists:table,field,delete_at,NOT_NULLも可。

別フィールドと同じ値か確認

パスワード再入力とかに利用?

same:other_field を使う。

値がそのテーブルの指定フィールドでまだ入っていない値かチェックする

メールアドレス重複などで利用する。

unique:table,field

  • メールアドレス重複の確認などで使う場合、ユーザ自身のidを省く必要がある。その方法。

    'unique:user,email,' . $user->id

  • idのフィールド名が違うなどの場合

    'unique:user,email,' . $user->id . ',user_id'

  • 有効になっているアカウントのみから絞り込む

    'unique:user,email,NULL,id,active,1'

    この場合は select count(*) from user where email = :input and active = 1 になる

今日より前の日付のみ受け付ける

多分こんな感じ。strtotimeDateTime にできる値ならいい。

'before:' . Carbon::now()->format('Y-m-d 00:00:00')

明日以降の日付のみ受け付ける

'after:' . Carbon::now()->addDay(1)->format('Y-m-d 00:00:00')

幾つかの値のみ受け付ける

A,B,C のいずれかのみ受け付ける

'in:' . implode(',', [ 'A', 'B', 'C' ])

幾つかの値以外を受け付ける

A,B,C 以外を受け付ける

not_in:A,B,C

半角数字のみ受け付ける

integer

有効なURLか確認する

active_url

パスワード確認

例えばパスワードフォームがpasswordで、validationルールにconfirmedがある場合、パスワード確認用フォームpassword_confirmationの値と比較をする。

例:

<div class="form-group">
    <label for="password" class="col-sm-2 control-label">新しいパスワード</label>
    <div class="col-sm-10">
        <?= Form::password( 'password', [
                'class' => "form-control",
                'id'    => 'password'
        ] ) ?>
    </div>
</div>

<div class="form-group">
    <label for="password_check" class="col-sm-2 control-label">新しいパスワード(確認)</label>
    <div class="col-sm-10">
        <?= Form::password( 'password_confirmation', [
                'class' => "form-control",
                'id'    => 'password_check'
        ] ) ?>
    </div>
</div>

バリデーションルールは下記のようにする

[
    'password' => 'required|confirmed|min:6'
]

チェックが入っている場合は必須にする

Aというチェックボックスにチェックが有れば、AText の値は必須にする

[
  'AText' => 'required_if:A,1'
]

チェックが入っている場合は入力してはいけない

Aというチェックボックスにチェックが有れば、AText の値は入っててはいけない

[
  'AText' => 'required_unless:A,1'
]

半角カタカナのみ受け付ける

ちょっと工夫が必要。AppServiceProviderboot メソッドに Validatorを拡張してkanaを追加して利用する。

AppServiceProvider.php
<?php

namespace App\Providers;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // カタカナのみ受け付ける
        \Validator::extend( "kana", function ($attribute, $value, $parameters, $validator){
            // 参考
            // http://pentan.info/php/reg/is_kana.html
            // http://aspiration.sakura.ne.jp/wiki/index.php?develop%2FUTF-8%E3%81%B2%E3%82%89%E3%81%8C%E3%81%AA%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A%E8%A1%A8
            // http://orange-factory.com/sample/utf8/code3-ef.html
            // \xef\xbc[\x90-\x99] => 全角数字
            // \xe3\x82[\xa1-\xbf]|\xe3\x83[\x80-\xbe] => カタカナ
            // \xef\xbd[\xa6-\xbf]|\xef\xbe[\x80-\x9f] => ヲ -> ゚ の半角カタカナ
            $regex = '{^(
                (\xe3\x82[\xa1-\xbf]) # カタカナ
               |(\xe3\x83[\x80-\xbe]) # カタカナ
               |(\xef\xbc[\x90-\x99]) # 全角数字
               |(\xef\xbd[\xa6-\xbf]) # 半角カタカナ
               |(\xef\xbe[\x80-\x9f]) # 半角カタカナ
               |[0-9a-zA-Z ]     # 半角英数字空白
               |(\xe3\x80\x80)   # 全角スペース
            )+$}x';
            $result = preg_match( $regex, $value, $match );
            if ($result === 1) {
                return true;
            }

            return false;
        } );
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

35
41
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
35
41