Qiita Conference 2025

鹿野壮 (@tonkotsuboy_com)

アウトプットは最強の自己投資 〜発信が人生とキャリアを変えた話〜

1
6

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 3 years have passed since last update.

laravelのユーザー登録画面でのバリデーション

Posted at

バリデーションを編集する方法です:point_up_tone2:

以下の階層からRegisterControllerへ入ってください。

.
└──laravel
    └── app
        └── Http
            └── Controllers
                └── Auth
                   └── RegisterController.php

<?php
// 略

class RegisterController extends Controller
{
    // 略
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }
    // 略
}

validatorメソッドの中身を見てみましょう。

name(ユーザー名)は、必須(required)、文字列(string)、最大255文字まで(max:255)といった定義となっています。

email(メールアドレス)は、メールアドレスの形式であること(email)、usersテーブルの他のメールアドレスと被らないこと(unique:users)といった定義も行なっています。

passwordは、最低8文字以上(min:8)、自分の項目名_confirmedという別の項目(つまり、password_confirmedという項目)と同じ値であること(confirmed)といった定義も行なっています。

以下のように編集してみましょう。

<?php
// 略
class RegisterController extends Controller
{
    // 略    
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'alpha_num', 'min:3', 'max:16', 'unique:users'], //-- この行を変更
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }
    // 略
}

追加されたバリデーションルールについて解説します。

alpha_numは、英数字であるかをチェックします。

alpha_num - Laravel公式

min:3は、3文字以上であるかをチェックします。

max:255については、max:16に変更しました。

unique:usersは、usersテーブルの他のレコードのnameカラムに、(ユーザー登録画面から)リクエストされたnameと同じ値が無いことをチェックします。

以上で編集完了です:relaxed:

1
6
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
1
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?