LoginSignup
19
24

More than 3 years have passed since last update.

【laravel】5.4 よく使いそうなバリデータ

Last updated at Posted at 2019-01-18
return Validator::make($data, [
    'email' => 'required|string|email|max:255|unique:users',
    'password' => 'required|string|min:6|confirmed',
]);

email は 必須|文字列形式|メールフォーマット|最大255文字|users テーブル内でユニーク
password は 必須|文字列形式|最小6文字|password_confirmationと同じ値

バリデーション 説明
numeric 数値
integer 整数値 |integer|min:1|max:100| 1≦整数≦100
digits:値 数値で値の桁数
alpha 英字のみ
alpha_dash 英字+ダッシュ(-)+下線(_)
alpha_num 英数字
regex:/^[!-~]+$/ 半角英数記号
regex:/\A(?=.?[a-z])(?=.?[A-Z])(?=.*?\d)[a-zA-Z\d]+\z/ 半角英小文字大文字数字をそれぞれ1種類以上含む

exists

'email' => 'exists:users,email,account_id,1'
'email' => 'exists:users,email,deleted,NULL'
'email' => 'exists:users,email,deleted,NOT_NULL'

email が users.email に存在、かつ account_id = 1
email が users.email に存在、かつ deleted = NULL。
email が users.email に存在、かつ deleted != NULL。

unique

'email' => 'unique:users,email,' . $user->id
'email' => 'unique:users,email,' . $user->user_id . ',user_id'
'email' => 'unique:users,email,' . $user->id . ',id,deleted,0'

email が users.email 内でユニーク かつ id != $user->id。
email が users.email 内でユニーク かつ user_id != $user->user_id。
email が users.email 内でユニーク かつ id != $user->id かつ deleted = 0

日付

バリデーション 説明
date strtotime を使って日付型かチェック
date_format date_parse_from_format を使って日付型かチェック。date と併用不可
after:日付 指定日付より後であること 日付は strtotime で処理。例) tomorrow
after_or_equal:日付 指定日付以降であること
before:日付 指定日付より前であること
before_or_equal:日付 指定日付以前であること

全角カナのカスタムバリエーション

AppServiceProvider.php の boot() に書くだけが簡単?

app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Validator;
    :
    public function boot()
    {
               :
        // カタカナチェック
        Validator::extend('katakana', function ($attribute, $value, $parameters, $validator) {
            $regex = '{^(
                 (\xe3\x82[\xa1-\xbf]) # カタカナ
                |(\xe3\x83[\x80-\xbe]) # カタカナ
            )+$}x';
            return (1 === preg_match($regex, $value, $match)) ? true : false;
        });
               :
    }

エラーメッセージも追加

resources/lang/ja/validation.php
    :
    'katakana' => ':attributeは全角カタカナを入力してください。',
    :

参考:https://readouble.com/laravel/5.4/ja/validation.html
- 目次 -

19
24
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
19
24