イントロダクションIntroduction
Laravelは入力されたデータに対するバリデーションの様々なアプローチを提供しています。Laravelの基本コントローラークラスはパワフルでバラエティー豊かなバリデーションルールを使いHTTPリクエストをバリデーションするために便利な手法を提供している、ValidatesRequests
トレイトをデフォルトで使用しています。Laravel provides several
different approaches to validate your application's
incoming data. By default, Laravel's base controller
class uses a ValidatesRequests
trait
which provides a convenient method to validate
incoming HTTP request with a variety of powerful
validation rules.
クイックスタートValidation Quickstart
パワフルなバリデーション機能を学ぶために、フォームバリデーションとユーザーにエラーメッセージを表示する完全な例を見てください。To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user.
ルート定義Defining The Routes
まず、app/Http/routes.php
ファイルに以下のルートを定義してあるとしましょう。First, let's assume we have the
following routes defined in our
app/Http/routes.php
file:
// ブログポストを作成するフォームの表示…
Route::get('post/create', 'PostController@create');
// 新しいブログポストを保存…
Route::post('post', 'PostController@store');
もちろん、GET
のルートは新しいブログポストを作成するフォームをユーザーへ表示し、POST
ルートで新しいブログポストをデータベースへ保存します。Of course, the GET
route will display a form for the user to create a
new blog post, while the POST
route
will store the new blog post in the
database.
コントローラー作成Creating The Controller
次に、これらのルートを処理する簡単なコントローラーを見てみましょう。今のところstore
メソッドは空のままです。Next, let's take a look at a
simple controller that handles these routes. We'll
leave the store
method empty for
now:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* 新ブログポスト作成フォームの表示
*
* @return Response
*/
public function create()
{
return view('post.create');
}
/**
* 新しいブログポストの保存
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
// ブログポストのバリデーションと保存…
}
}
バリデーションロジックWriting The Validation Logic
これで新しいブログポストに対するバリデーションロジックをstore
メソッドに埋め込む準備ができました。アプリケーションの基本コントローラー(App\Http\Controllers\Controller
)クラスを調べてみれば、ValidatesRequests
トレイトを使っているのが分かるでしょう。このトレイトは全てのコントローラーに対して、便利なvalidate
メソッドを提供しています。Now we are ready to fill in our
store
method with the logic to validate
the new blog post. If you examine your application's
base controller
(App\Http\Controllers\Controller
)
class, you will see that the class uses a
ValidatesRequests
trait. This trait
provides a convenient validate
method
in all of your controllers.
validate
メソッドはHTTPリクエストとバリデーションルールを受け取ります。バリデーションに適合するとそのまま続けてコードが実行されます。しかし、バリデーションに失敗すると例外が投げられ、適当なエラーレスポンスが自動的にユーザーに送り返されます。伝統的なHTTPリクエストの場合はリダイレクトが生成され、AJAXリクエストの場合はJSONレスポンスが送られます。The validate
method
accepts an incoming HTTP request and a set of
validation rules. If the validation rules pass, your
code will keep executing normally; however, if
validation fails, an exception will be thrown and
the proper error response will automatically be sent
back to the user. In the case of a traditional HTTP
request, a redirect response will be generated,
while a JSON response will be sent for AJAX
requests.
validate
メソッドをもっとよく理解するため、store
メソッドに取り掛かりましょう。To get a better understanding of
the validate
method, let's jump back
into the store
method:
/**
* 新しいブログポストの保存
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// ブログポストは有効なので、データベースに保存する…
}
ご覧の通り、HTTPリクエストと希望のバリデーションルールをvalidate
メソッドに渡しているだけです。繰り返しますが、バリデーションに失敗すれば、適当なレスポンスが自動的に生成されます。バリデーションに合格すれば、コントローラーは普通に実行されます。As you can see, we simply pass
the incoming HTTP request and desired validation
rules into the validate
method. Again,
if the validation fails, the proper response will
automatically be generated. If the validation
passes, our controller will continue executing
normally.
ネストした属性の注意点A Note On Nested Attributes
HTTPリクエストに「ネスト」したパラメーターが含まれている場合、バリデーションルールは「ドット」記法により指定します。If your HTTP request contains "nested" parameters, you may specify them in your validation rules using "dot" syntax:
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
バリデーションエラー表示Displaying The Validation Errors
ではやって来たリクエストの入力が指定したバリデーションルールに当てはまらなかった場合はどうなるんでしょう? 既に説明した通り、Laravelは自動的にユーザーを以前のページヘリダイレクトします。付け加えて、バリデーションエラーは全部自動的にフラッシュデータとしてセッションへ保存されます。So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session[/docs/{{version}}/session#flash-data].
GET
ルートのビューへエラーメッセージを明示的に結合する必要がないことにも注目してください。これはつまり、Laravelはいつもセッションデータの中にエラーの存在をチェックしており、見つけた場合は自動的に結合しているからです。つまり、**全リクエストの全ビューで、いつでも$errors
変数は利用できるのが、重要なポイントです。**いつでも$erroes
変数が定義されていると仮定でき、安全に利用できるのです。$errors
はIlluminate\Support\MessageBag
のインスタンスです。このオブジェクトの詳細は、このドキュメントの後半で説明しています。Again, notice that we did not
have to explicitly bind the error messages to the
view in our GET
route. This is because
Laravel will always check for errors in the session
data, and automatically bind them to the view if
they are available. So, it is important to
note that an $errors
variable will
always be available in all of your views on
every request, allowing you to
conveniently assume the $errors
variable is always defined and can be safely used.
The $errors
variable will be an
instance of
Illuminate\Support\MessageBag
. For more
information on working with this object, check
out its
documentation[#working-with-error-messages].
この例では、バリデーションに失敗すると、エラーメッセージをビューで表示できるように、コントローラーのcreate
メソッドにリダイレクトされることになります。So, in our example, the user will
be redirected to our controller's
create
method when validation fails,
allowing us to display the error messages in the
view:
<!-- /resources/views/post/create.blade.php -->
<h1>ポスト作成</h1>
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<!-- ポスト作成フォーム -->
フラッシュエラーメッセージのカスタマイズCustomizing The Flashed Error Format
バリデーション失敗時にセッションへフラッシュデータとして保存されるバリデーションエラーのフォーマットをカスタマイズしたい場合は、基本コントローラーのformatValidationErrors
をオーバーライドしてください。Illuminate\Contracts\Validation\Validator
クラスをファイルにインポートするのを忘れないでください。If you wish to customize the
format of the validation errors that are flashed to
the session when validation fails, override the
formatValidationErrors
on your base
controller. Don't forget to import the
Illuminate\Contracts\Validation\Validator
class at the top of the file:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController
{
use DispatchesJobs, ValidatesRequests;
/**
* {@inheritdoc}
*/
protected function formatValidationErrors(Validator $validator)
{
return $validator->errors()->all();
}
}
AJAXリクエストとバリデーションAJAX Requests & Validation
この例ではアプリケーションにデータを送るために伝統的なフォームを使いました。しかし、多くのアプリケーションでAJAXリクエストが使用されています。AJAXリクエストにvalidate
メソッドを使う場合、Laravelはリダイレクトレスポンスを生成しません。代わりにバリデーションエラーを全部含んだJSONレスポンスを生成します。このJSONレスポンスは422
HTTPステータスコードで送られます。In this
example, we used a traditional form to send data to
the application. However, many applications use AJAX
requests. When using the validate
method during an AJAX request, Laravel will not
generate a redirect response. Instead, Laravel
generates a JSON response containing all of the
validation errors. This JSON response will be sent
with a 422 HTTP status code.
他のバリデーションアプローチOther Validation Approaches
Validatorを自分で作成Manually Creating Validators
ValidatesRequests
トレイトのvalidate
メソッドを使いたくなければ、Validator
ファサードを使い、バリデーターインスタンスを自分で作成してください。このファサードのmake
メソッドで、新しいインスタンスを生成できます。If you do not want to use the
ValidatesRequests
trait's
validate
method, you may create a
validator instance manually using the
Validator
facade[/docs/{{version}}/facades]. The
make
method on the facade generates a
new validator instance:
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* 新ポストの保存
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// ブログポストの保存…
}
}
make
メソッドの第1引数は、バリデーションを行うデータです。第2引数はそのデータに適用するバリデーションルールです。The first argument passed to the
make
method is the data under
validation. The second argument is the validation
rules that should be applied to the data.
リクエストがバリデーションを通過できなかった後に、セッションにエラーメッセージをフラッシュデータとして保存するためにwithErrors
メソッドを使ってください。このメソッドを使うと、簡単にユーザーに情報を表示できるようにするため、リダイレクトの後でビューに対し$errors
変数を自動的に共有します。withErrors
メソッドはバリデーターかMessageBag
、PHPの配列を受け取ります。After checking if the request
failed to pass validation, you may use the
withErrors
method to flash the error
messages to the session. When using this method, the
$errors
variable will automatically be
shared with your views after redirection, allowing
you to easily display them back to the user. The
withErrors
method accepts a validator,
a MessageBag
, or a PHP
array
.
名前付きエラーバッグNamed Error Bags
1ページの中に複数のフォームを入れている場合は、特定のフォームのエラーメッセージを受け取れるように、MessageBag
へ名前を付けてください。withErrors
の第2引数に名前を渡すだけです。If you have multiple forms on a
single page, you may wish to name the
MessageBag
of errors, allowing you to
retrieve the error messages for a specific form.
Simply pass a name as the second argument to
withErrors
:
return redirect('register')
->withErrors($validator, 'login');
$errors
変数を使い、名前を付けたMessageBag
インスタンスへアクセスできます。You may then access the named
MessageBag
instance from the
$errors
variable:
{{ $errors->login->first('email') }}
バリデーション後のフックAfter Validation Hook
バリデターにはさらに、バリデーションが終了した時点で実行するコールバックを付け加えられます。これにより、追加のバリデーションを行い、さらにエラーメッセージコレクションにエラーメッセージを追加することが簡単にできます。バリデターインスタンスのafter
メソッドを使ってみましょう。The validator also allows you to
attach callbacks to be run after validation is
completed. This allows you to easily perform further
validation and even add more error messages to the
message collection. To get started, use the
after
method on a validator
instance:
$validator = Validator::make(...);
$validator->after(function($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'このフィールドで何か間違いが起こった!');
}
});
if ($validator->fails()) {
//
}
フォームリクエストバリデーションForm Request Validation
より複雑なバリデーションのシナリオでは、「フォームリクエスト」を生成したほうが良いでしょう。フォームリクエストは、バリデーションロジックを含んだカスタムリクエストクラスです。フォームリクエストクラスを作成するには、make:request
Artisan CLIコマンドを使用します。For more
complex validation scenarios, you may wish to create
a "form request". Form requests are custom
request classes that contain validation logic. To
create a form request class, use the
make:request
Artisan CLI
command:
php artisan make:request StoreBlogPostRequest
生成されたクラスは、app/Http/Request
ディレクトリーへ設置されます。では、バリデーションルールを少しrules
メソッドへ追加してみましょう。The generated class will be
placed in the app/Http/Requests
directory. Let's add a few validation rules to the
rules
method:
/**
* リクエストに適用するバリデーションルールを取得
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
では、どのようにバリデーションルールを実行するのでしょうか?必要なのは、コントローラーのメソッドで、このリクエストをタイプヒントで指定することです。やって来たフォームリクエストはコントローラーメソッドが呼び出される前にバリデーションを行います。つまり、コントローラーにバリデーションロジックを取っ散らかす必要はありません。So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:
/**
* ブログポストの保存
*
* @param StoreBlogPostRequest $request
* @return Response
*/
public function store(StoreBlogPostRequest $request)
{
// やって来たリクエストは正しい…
}
バリデーションに失敗すると、前のアドレスにユーザーを戻すために、リダイレクトレスポンスが生成されます。エラーも表示できるように、フラッシュデーターとしてセッションに保存されます。もしリクエストがAJAXリクエストであれば、バリデーションエラーを表現するJSONを含んだ、422ステータスコードのHTTPレスポンスがユーザーに返されます。If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
フォームリクエスト権限Authorizing Form Requests
フォームリクエストクラスはauthorize
メソッドも用意しています。このメソッドでは認証されているユーザーが、指定されたリソースを更新する権限を実際に持っているのかを確認します。たとえばユーザーがブログポストのコメントを更新しようとしているなら、本人のコメントなのでしょうか?
調べてみましょう。The form request class
also contains an authorize
method.
Within this method, you may check if the
authenticated user actually has the authority to
update a given resource. For example, if a user is
attempting to update a blog post comment, do they
actually own that comment? For example:
/**
* ユーザーがこのリクエストの権限を持っているかを判断する
*
* @return bool
*/
public function authorize()
{
$commentId = $this->route('comment');
return Comment::where('id', $commentId)
->where('user_id', Auth::id())->exists();
}
上例の中のroute
メソッド呼び出しに注目してください。このメソッドで、例えば{comment}
パラメーターのような、呼びだされているルートのURIパラメーター定義にアクセスさせてくれます。Note the call to the
route
method in the example above. This
method grants you access to the URI parameters
defined on the route being called, such as the
{comment}
parameter in the example
below:
Route::post('comment/{comment}');
authorize
メソッドがfalse
を返すと、403ステータスコードのHTTPレスポンスが自動的に返され、コントローラーメソッドは実行されません。If the authorize
method returns false
, a HTTP response
with a 403 status code will automatically be
returned and your controller method will not
execute.
アプリケーションの他の場所で認証のロジックを行おうと設計しているのでしたら、シンプルにauthorize
メソッドからtrue
を返してください。If you plan to have authorization
logic in another part of your application, simply
return true
from the
authorize
method:
/**
* ユーザーがこのリクエストの権限を持っているかを判断する
*
* @return bool
*/
public function authorize()
{
return true;
}
フラッシュデータとして保存されるエラー形式のカスタマイズCustomizing The Flashed Error Format
バリデーションが失敗した時にフラッシュデーターとして保存されるバリデーションエラーの形式をカスタマイズしたければ、基本コントローラー(App\Http\Requests\Request
)のformatErrors
をオーバーライドしてください。Illuminate\Contracts\Validation\Validator
クラスをファイルの先頭でインポートするのを忘れないでください。If you wish to customize the
format of the validation errors that are flashed to
the session when validation fails, override the
formatErrors
on your base request
(App\Http\Requests\Request
). Don't
forget to import the
Illuminate\Contracts\Validation\Validator
class at the top of the file:
/**
* {@inheritdoc}
*/
protected function formatErrors(Validator $validator)
{
return $validator->errors()->all();
}
エラーメッセージのカスタマイズCustomizing The Error Messages
フォームリクエストにより使用されているメッセージはmessage
メソッドをオーバーライドすることによりカスタマイズできます。このメソッドから属性/ルールと対応するエラーメッセージのペアを配列で返してください。You may customize the error
messages used by the form request by overriding the
messages
method. This method should
return an array of attribute / rule pairs and their
corresponding error messages:
/**
* 定義済みバリデーションルールのエラーメッセージ取得
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'タイトルが必要です。',
'body.required' => 'メッセージが必要です。',
];
}
エラーメッセージの操作Working With Error Messages
Validator
のインスタンスに対しmessages
メソッドを呼びだせば、エラーメッセージを操作するのに便利な様々なメソッドを持つMessageBag
インスタンスが取得できます。After calling the
errors
method on a
Validator
instance, you will receive an
Illuminate\Support\MessageBag
instance,
which has a variety of convenient methods for
working with error messages.
指定フィールドの最初のエラーメッセージ取得Retrieving The First Error Message For A Field
指定したフィールドの最初のエラーメッセージを取得するには、first
メソッドを使います。To retrieve the first error
message for a given field, use the
first
method:
$messages = $validator->errors();
echo $messages->first('email');
指定フィールドの全エラーメッセージ取得Retrieving All Error Messages For A Field
指定したフィールドの全エラーメッセージを配列で取得したい場合は、get
メソッドを使います。If you wish to simply retrieve an
array of all of the messages for a given field, use
the get
method:
foreach ($messages->get('email') as $message) {
//
}
全フィールドの全エラーメッセージ取得Retrieving All Error Messages For All Fields
全フィールドの全メッセージの配列を取得したい場合は、all
メソッドを使います。To retrieve an array of all
messages for all fields, use the all
method:
foreach ($messages->all() as $message) {
//
}
指定フィールドのメッセージ存在確認Determining If Messages Exist For A Field
if ($messages->has('email')) {
//
}
エラーメッセージのフォーマットを指定し取得Retrieving An Error Message With A Format
echo $messages->first('email', '<p>:message</p>');
全エラーメッセージをフォーマット指定し取得Retrieving All Error Messages With A Format
foreach ($messages->all('<li>:message</li>') as $message) {
//
}
カスタムエラーメッセージCustom Error Messages
必要であればバリデーションでデフォルトのメッセージの代わりに、カスタムエラーメッセージを使うことができます。カスタムメッセージを指定するにはいくつか方法があります。最初の方法はValidator::make
メソッドの第3引数として、カスタムメッセージを渡す方法です。If needed, you may use custom
error messages for validation instead of the
defaults. There are several ways to specify custom
messages. First, you may pass the custom messages as
the third argument to the
Validator::make
method:
$messages = [
'required' => ':attributeフィールドは必須です。',
];
$validator = Validator::make($input, $rules, $messages);
この例中のattribute
プレースホルダーはバリデーション対象のフィールドの名前に置き換えられます。バリデーションメッセージ中で他のプレースホルダーを使うこともできます。例を見てください。In this example, the
:attribute
place-holder will be
replaced by the actual name of the field under
validation. You may also utilize other place-holders
in validation messages. For example:
$messages = [
'same' => ':attributeと:otherは一致している必要があります。',
'size' => ':attributeはぴったり:sizeである必要があります。',
'between' => ':attributeはminから:maxの間である必要があります。',
'in' => ':attribute以降のタイプのどれかである必要があります。 :values',
];
指定フィールドにカスタムメッセージ指定Specifying A Custom Message For A Given Attribute
時々特定のフィールドに対するカスタムエラーメッセージを指定したい場合があります。「ドット」記法を使用し行います。属性名が最初で、続いてルールをつなげます。Sometimes you may wish to specify a custom error messages only for a specific field. You may do so using "dot" notation. Specify the attribute's name first, followed by the rule:
$messages = [
'email.required' => 'あなたのメールアドレスを教えてもらう必要があります!',
];
言語ファイルでカスタムメッセージ指定Specifying Custom Messages In Language Files
多くの場合、Validator
に直接カスタムメッセージを渡すよりは言語ファイルに指定したいですよね。ならばresources/lang/xx/validation.php
言語ファイルのcustom
配列にメッセージを追加してください。In many cases, you may wish to
specify your attribute specific custom messages in a
language file instead of passing them directly to
the Validator
. To do so, add your
messages to custom
array in the
resources/lang/xx/validation.php
language file.
'custom' => [
'email' => [
'required' => 'あなたのメールアドレスを教えてもらう必要があります!',
],
],
使用可能なバリデーションルールAvailable Validation Rules
使用可能な全バリデーションルールとその機能の一覧です。Below is a list of all available validation rules and their function:
acceptedaccepted
そのフィールドがyes、on、1、trueであることをバリデートします。これは「サービス利用規約」同意のバリデーションに便利です。The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.
active_urlactive_url
フィルドがPHPの機能であるcheckdnsrr
を通して、有効なURLであるかをバリデートします。The field under validation must
be a valid URL according to the
checkdnsrr
PHP function.
after:日付after:date
フィールドの値が与えられた日付以降であるかバリデーションします。日付はPHPのstrtotime
関数で処理されます。The field under validation must
be a value after a given date. The dates will be
passed into the strtotime
PHP
function:
'start_date' => 'required|date|after:tomorrow'
strtotime
により評価される日付文字列を渡す代わりに、その日付と比較する他のフィールドを指定することもできます。Instead of passing a date string
to be evaluated by strtotime
, you may
specify another field to compare against the
date:
'finish_date' => 'required|date|after:start_date'
alphaalpha
フィールドが全部アルファベット文字であることをバリデートします。The field under validation must be entirely alphabetic characters.
alpha_dashalpha_dash
フィールドが全部アルファベット文字とダッシュ(-)、下線(_)であることをバリデートします。The field under validation may have alpha-numeric characters, as well as dashes and underscores.
alpha_numalpha_num
フィールドが全部アルファベット文字と数字であることをバリデートします。The field under validation must be entirely alpha-numeric characters.
arrayarray
フィールドが配列タイプであることをバリデートします。The
field under validation must be a PHP
array
.
before:日付before:date
フィールドが与えられた日付より前であることをバリデートします。日付はPHPのstrtotime
関数で処理されます。The field under validation must
be a value preceding the given date. The dates will
be passed into the PHP strtotime
function.
between:min,maxbetween:min,max
フィールドが指定された最小値と最大値の間のサイズであることをバリデートします。size
ルールと同様の判定方法で、文字列、数値、ファイルは評価されます。The field under validation must
have a size between the given min and
max. Strings, numerics, and files are
evaluated in the same fashion as the
size
[#rule-size]
rule.
booleanboolean
フィールドが論理値として有効であることをバリデートします。受け入れられる入力は、true
、false
、1
、0
、"1"
、"0"
です。The field under validation must
be able to be cast as a boolean. Accepted input are
true
, false
,
1
, 0
,
"1"
, and
"0"
.
confirmedconfirmed
フィールドがそのフィールド名+_confirmation
フィールドと同じ値であることをバリデートします。例えば、バリデーションするフィールドがpassword
であれば、同じ値のpassword_confirmation
フィールドが入力に存在していなければなりません。The field under validation must
have a matching field of
foo_confirmation
. For example, if the
field under validation is password
, a
matching password_confirmation
field
must be present in the input.
datedate
パリデーションされる値はPHP関数のstrtotime
を使用し確認されます。The field under validation must
be a valid date according to the
strtotime
PHP function.
date_format:フォーマットdate_format:format
バリデーションされる値がフォーマット定義と一致するか、PHP関数のdate_parse_from_format
を使用し確認されます。バリデーション時にはdate
かdate_format
のどちらかを使用しなくてはならず、両方はできません。The field under validation must
match the given format. The format will be
evaluated using the PHP
date_parse_from_format
function. You
should use either date
or date_format
when validating a field,
not both.
different:フィールドdifferent:field
フィールドが指定されたフィールドと異なった値を指定されていることをバリデートします。The field under validation must have a different value than field.
digits:値digits:value
フィールドが数値で、値の桁数であることをバリデートします。The field under validation must be numeric and must have an exact length of value.
digits_between:最小値,最大値digits_between:min,max
フィールドが整数で、桁数が最小値から最大値の間であることをバリデートします。The field under validation must have a length between the given min and max.
emailemail
フィールドがメールアドレスとして正しいことをバリデートします。The field under validation must be formatted as an e-mail address.
exists:テーブル,カラムexists:table,column
フィールドの値が、指定されたデータベーステーブルに存在することをバリデートします。The field under validation must exist on a given database table.
基本的なExistsルールの使用法Basic Usage Of Exists Rule
'state' => 'exists:states'
カスタムカラム名の指定Specifying A Custom Column Name
'state' => 'exists:states,abbreviation'
さらにクエリーへWHERE節として追加される条件を追加することも可能です。You may also specify more conditions that will be added as "where" clauses to the query:
'email' => 'exists:staff,email,account_id,1'
"WHERE"節にNULL
かNOT_NULL
を渡すことも可能です。You may also pass
NULL
or NOT_NULL
to the
"where" clause:
'email' => 'exists:staff,email,deleted_at,NULL'
'email' => 'exists:staff,email,deleted_at,NOT_NULL'
imageimage
フィールドで指定されたファイルが画像(jpg、png、bmp、gif、svg)であることをバリデートします。The file under validation must be an image (jpeg, png, bmp, gif, or svg)
in:foo,bar...in:foo,bar,...
フィールドが指定されたリストの中の値に含まれていることをバリデートします。The field under validation must be included in the given list of values.
integerinteger
フィールドが整数値であることをバリデートします。The field under validation must be an integer.
ipip
フィールドがIPアドレスの形式として正しいことをバリデートします。The field under validation must be an IP address.
jsonjson
フィールドが有効なJSON文字列であることをバリデートします。The field under validation must be a valid JSON string.
max:値max:value
フィールドが最大値として指定された値以下であることをバリデートします。size
ルールと同様の判定方法で、文字列、数値、ファイルが評価されます。The field under validation must
be less than or equal to a maximum value.
Strings, numerics, and files are evaluated in the
same fashion as the
size
[#rule-size]
rule.
mimes:foo,bar,...mimes:foo,bar,...
フィールドで指定されたファイルが拡張子のリストの中のMIMEタイプのどれかと一致することをバリデートします。The file under validation must have a MIME type corresponding to one of the listed extensions.
mimesルールの基本的な使用法Basic Usage Of MIME Rule
'photo' => 'mimes:jpeg,bmp,png'
拡張子だけを限定する必要があるとしても、このルールはファイルのMIMEタイプに基づき、ファイルの内容を読み、MIMEタイプを推測することでバリデーションを行います。Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file's contents and guessing its MIME type.
MIMEタイプと対応する拡張子の完全なリストは、http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.typesで確認できます。A full listing of MIME types and their corresponding extensions may be found at the following location: http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types[http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types]
min:値min:value
フィールドが最小値として指定された値以上であることをバリデートします。size
ルールと同様の判定方法で、文字列、数値、ファイルが評価されます。The field under validation must
have a minimum value. Strings, numerics,
and files are evaluated in the same fashion as the
size
[#rule-size]
rule.
not_in:foo,bar,...not_in:foo,bar,...
フィールドが指定されたリストの中の値に含まれていないことをバリデートします。The field under validation must not be included in the given list of values.
numericnumeric
フィールドは数値であることをバリデートします。The field under validation must be numeric.
regex:正規表現regex:pattern
フィールドが指定された正規表現にマッチすることをバリデートします。The field under validation must match the given regular expression.
注目:
regex
パターンを使用する場合はルールをパイプ(縦棒)で区切らず、配列で指定する必要があります。特に正規表現に縦棒を含んでいる場合に該当します。Note: When using
the regex
pattern, it may be necessary
to specify rules in an array instead of using pipe
delimiters, especially if the regular expression
contains a pipe character.
requiredrequired
フィールドが入力に存在しており、かつ空でないことをバリデートします。フィールドは以下の要件がtrueの場合に「空」であると判断されます。The field under validation must be present in the input data and not empty. A field is considered "empty" is one of the following conditions are true:
- 値が
null
である。The value isnull
. - 値が空文字列である。The value is an empty string.
- 値が空の配列か、空の
Countable
オブジェクトである。The value is an empty array or emptyCountable
object. - 値がパスのないアップロード済みファイルである。The value is an uploaded file with no path.
required_if:他のフィールド,値,...required_if:anotherfield,value,...
引数で指定された他のフィールドフィールドが、値のどれかを持っている場合に、このフィールドが入力されていることをバリデートします。The field under validation must be present if the anotherfield field is equal to any value.
required_unless:他のフィールド,値,...required_unless:anotherfield,value,...
引数で指定された他のフィールドフィールドが、値のどれとも一致しない場合に、このフィールドが入力されていることをバリデートします。The field under validation must be present unless the anotherfield field is equal to any value.
required_with:foo,bar,...required_with:foo,bar,...
引数で指定されたフィールドのうち、どれかが存在している場合のみ、フィールドが入力されていることをバリデートします。The field under validation must be present only if any of the other specified fields are present.
required_with_all:foo,bar,...required_with_all:foo,bar,...
引数で指定されたフィールドのうち、全てが存在している場合のみ、フィールドが入力されていることをバリデートします。The field under validation must be present only if all of the other specified fields are present.
required_without:foo,bar,...required_without:foo,bar,...
フィールドは、指定された他のフィールドのうちどれかが存在しない場合のみ、この項目が入力されていることをバリデートします。The field under validation must be present only when any of the other specified fields are not present.
required_without_all:foo,bar,...required_without_all:foo,bar,...
フィールドは、指定された他のフィールド全部が存在しない場合のみ、この項目が入力されていることをバリデートします。The field under validation must be present only when all of the other specified fields are not present.
same:フィールドsame:field
フィールドが、指定されたフィールドと同じ値であることをバリデートします。The given field must match the field under validation.
size:値size:value
フィールドは指定された値と同じサイズであることをバリデートします。文字列の場合、値は文字長です。数値項目の場合、値は整数値です。ファイルの場合、値はキロバイトのサイズです。The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For files, size corresponds to the file size in kilobytes.
stringstring
フィルードは文字列タイプであることをバリデートします。The field under validation must be a string.
timezonetimezone
timezone_identifiers_list
PHP関数の値に基づき、フィールドがタイムゾーンとして識別されることをバリデートします。The field under
validation must be a valid timezone
identifier according to the
timezone_identifiers_list
PHP function.
unique:テーブル,カラム,除外ID,IDカラムunique:table,column,except,idColumn
フィールドは指定されたデータベースで一意であることをバリデートします。column
オプションが指定されない場合、フィールド名が使用されます。The field under
validation must be unique on a given
database table. If the
column
option is not
specified, the field name will be
used.
カスタムカラム名の指定Specifying A Custom Column Name:
'email' => 'unique:users,email_address'
カスタムデータベース接続Custom Database Connection
場合により、バリデーターにより生成されるデータベースクエリーに、カスタム接続を設定する必要があるかもしれません。上記のバリデーションルール、unique:users
ではクエリーに対し、デフォルトデータベース接続が使用されます。これをオーバーライドするにはテーブル名に続け、ドット記法で接続を指定してください。Occasionally, you
may need to set a custom connection
for database queries made by the
Validator. As seen above, setting
unique:users
as a
validation rule will use the default
database connection to query the
database. To override this, specify
the connection followed by the table
name using "dot"
syntax:
'email' => 'unique:connection.users,email_address'
指定されたIDのuniqueルールを無視するForcing A Unique Rule To Ignore A Given ID:
uniqueチェックで指定したIDを除外したい場合があります。たとえばユーザー名、メールアドレス、それと住所の「プロフィール更新」の状況を考えてください。もちろん、メールアドレスは一意であることを確認したいと思います。しかし、もしユーザーが名前フィールドだけ変更し、メールフィールドを変更しなければ、そのユーザーが既にそのメールアドレスの所有者として登録されているために起きるバリデーションエラーを避けたいと思うでしょう。他のユーザーによって既に使用されているメールアドレスがユーザーにより指定された場合のみ、バリデーションエラーが起きてもらいたいでしょう。uniqueルールに無視するユーザーのIDを指定するには、第3パラメーターとして指定してください。Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address. You only want to throw a validation error if the user provides an e-mail address that is already used by a different user. To tell the unique rule to ignore the user's ID, you may pass the ID as the third parameter:
'email' => 'unique:users,email_address,'.$user->id
テーブルで使用している主キーがid
ではない場合、第4パラメーターとして指定子ます。If your table
uses a primary key column name other
than id
, you may
specify it as the fourth
parameter:
'email' => 'unique:users,email_address,'.$user->id.',user_id'
追加のWHERE節を付け加えるAdding Additional Where Clauses:
さらにクエリーの"where"節として追加の検索条件を付け加えることもできます。You may also specify more conditions that will be added as "where" clauses to the query:
'email' => 'unique:users,email_address,NULL,id,account_id,1'
上のルールでは、account_id
が1
のレコードのみuniqueチェックに使用されます。In the rule
above, only rows with an
account_id
of
1
would be included in
the unique check.
urlurl
PHPのfilter_var
関数により、URLが正しいかをバリデートします。The field under
validation must be a valid URL
according to PHP's
filter_var
function.
条件付きでルールを追加するConditionally Adding Rules
ある状況ではそのフィールドが入力配列の中に存在する場合のみ、バリデーションを実行したいことがあると思います。これを簡単に行うには、sometimes
ルールを追加してください。In some
situations, you may wish to run
validation checks against a field
only if that field
is present in the input array. To
quickly accomplish this, add the
sometimes
rule to your
rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);
上の例ではemail
フィールドが、$data
配列の中に存在している場合のみバリデーションが実行されます。In the example
above, the email
field
will only be validated if it is
present in the $data
array.
複雑な条件のバリデーションComplex Conditional Validation
時々もっと複雑な条件のロジックによりバリデーションルールを追加したい場合もあります。たとえば他のフィールドが100より大きい場合のみ、指定したフィールドが入力されているかをバリデートしたいときなどです。もしくは2つのフィールドのどちらか一方が存在する場合は、両方共に値を指定する必要がある場合です。こうしたルールを付け加えるのも面倒ではありません。最初にValidator
インスタンスを生成するのは、固定ルールの場合と同じです。Sometimes you may
wish to add validation rules based
on more complex conditional logic.
For example, you may wish to require
a given field only if another field
has a greater value than 100. Or,
you may need two fields to have a
given value only when another field
is present. Adding these validation
rules doesn't have to be a pain.
First, create a
Validator
instance with
your static rules that
never change:
$v = Validator::make($data, [
'email' => 'required|email',
'games' => 'required|numeric',
]);
ゲームコレクターのためのWebアプリケーションだと仮定しましょう。ゲームコレクターがアプリケーションに登録する時に、100ゲーム以上所有しているのであれば、なぜそんなに多く持っているのか理由を説明してもらいます。たとえば中古ゲーム店を運営しているのかも知れませんし、ただ収集家なのかも知れません。この条件付きの要求を追加するためにValidator
インスタンスへ、sometimes
メソッドを使用してください。Let's assume our
web application is for game
collectors. If a game collector
registers with our application and
they own more than 100 games, we
want them to explain why they own so
many games. For example, perhaps
they run a game re-sell shop, or
maybe they just enjoy collecting. To
conditionally add this requirement,
we can use the
sometimes
method on the
Validator
instance.
$v->sometimes('reason', 'required|max:500', function($input) {
return $input->games >= 100;
});
sometimes
メソッドの最初の引数は条件付きでバリデーションを行うフィールドの名前です。2つ目の引数は追加したいルールです。3つ目の引数にクロージャーが渡され、true
を返したらそのルールは追加されます。このメソッドにより複雑な条件付きのバリデーションが簡単に作成できます。一度に多くのフィールドに、条件付きバリデーションを追加することもできます。The first
argument passed to the
sometimes
method is the
name of the field we are
conditionally validating. The second
argument is the rules we want to
add. If the Closure
passed as the third argument returns
true
, the rules will be
added. This method makes it a breeze
to build complex conditional
validations. You may even add
conditional validations for several
fields at once:
$v->sometimes(['reason', 'cost'], 'required', function($input) {
return $input->games >= 100;
});
注目: クロージャーに渡される
$input
パラメーターはIlluminate\Support\Fluent
のインスタンスで、フィールドと入力値にアクセスするためのオブジェクトです。Note: The$input
parameter passed to yourClosure
will be an instance ofIlluminate\Support\Fluent
and may be used to access your input and files.
カスタムバリデーションルールCustom Validation Rules
Laravelは様々な役に立つバリデーションルールを提供しています。しかし自分自身の特別なルールも使いたいですよね。カスタムバリデーションルールを追加する一つの方法は、Validator
ファサードのextend
を使う方法です。カスタムバリデーションルールを追加するために、サービスプロバイダーの中でこのメッセージを使ってみましょう。Laravel provides
a variety of helpful validation
rules; however, you may wish to
specify some of your own. One method
of registering custom validation
rules is using the
extend
method on the
Validator
facade[/docs/{{version}}/facades].
Let's use this method within a
service
provider[/docs/{{version}}/providers]
to register a custom validation
rule:
<?php
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* アプリケーションサービスの初期処理
*
* @return void
*/
public function boot()
{
Validator::extend('foo', function($attribute, $value, $parameters, $validator) {
return $value == 'foo';
});
}
/**
* サービスプロバイダー登録
*
* @return void
*/
public function register()
{
//
}
}
カスタムバリデーターのクロージャーは4つの引数を取ります。$attribute
はバリデーションをしているフィールド、$value
はその値、$parameters
はルールに渡された引数、最後はValidator
インスタンスです。The custom
validator Closure receives four
arguments: the name of the
$attribute
being
validated, the $value
of the attribute, an array of
$parameters
passed to
the rule, and the
Validator
instance.
クロージャーの代わりにextend
メソッドへクラスとメソッドを渡すこともできます。You may also pass
a class and method to the
extend
method instead
of a Closure:
Validator::extend('foo', 'FooValidator@validate');
エラーメッセージの定義Defining The Error Message
カスタムルールに対するエラーメッセージを定義する必要もあります。インラインでカスタムエラーの配列を使うか、バリデーション言語ファイルにエントリーを追加するどちらかで行えます。このメッセージは属性とエラーメッセージを指定するだけの一次配列で、「カスタマイズ」した配列を入れてはいけません。You will also
need to define an error message for
your custom rule. You can do so
either using an inline custom
message array or by adding an entry
in the validation language file.
This message should be placed in the
first level of the array, not within
the custom
array, which
is only for attribute-specific error
messages:
"foo" => "入力は不正です!",
"accepted" => ":attributeは受け入れられません。",
// その他のバリデーションメッセージ
カスタムバリデーションルールを作成する場合、エラーメッセージのカスタムプレースフォルダーも定義したいことがあります。前記の方法でカスタムバリデターを作成し、それからValidator
ファサードのreplacer
メソッドを呼びだしてください。これはサービスプロバイダーのboot
メソッドの中で行います。When creating a
custom validation rule, you may
sometimes need to define custom
place-holder replacements for error
messages. You may do so by creating
a custom Validator as described
above then making a call to the
replacer
method on the
Validator
facade. You
may do this within the
boot
method of a
service
provider[/docs/{{version}}/providers]:
/**
* アプリケーションサービスの初期起動処理
*
* @return void
*/
public function boot()
{
Validator::extend(...);
Validator::replacer('foo', function($message, $attribute, $rule, $parameters) {
return str_replace(...);
});
}
暗黙の拡張Implicit Extensions
バリデートする属性が存在していない場合か、required
ルールで定義している「空」の場合、カスタム拡張したものも含め、通常のバリデーションルールは実行されません。たとえばinteger
ルールはnull
値に対して実行されません。By default, when
an attribute being validated is not
present or contains an empty value
as defined by the
required
[#rule-required]
rule, normal validation rules,
including custom extensions, are not
run. For example, the
integer
[#rule-integer]
rule will not be run against a
null
value:
$rules = ['count' => 'integer'];
$input = ['count' => null];
Validator::make($input, $rules)->passes(); // true
属性が空であってもルールを実行するということは、その属性が必須であることを暗黙のうちに示しています。このような「暗黙の」拡張を作成するには、Validator::extendImplicit()
メソッドを使います。For a rule to run
even when an attribute is empty, the
rule must imply that the attribute
is required. To create such an
"implicit" extension, use
the
Validator::extendImplicit()
method:
Validator::extendImplicit('foo', function($attribute, $value, $parameters, $validator) {
return $value == 'foo';
});
注意: 「暗黙の」拡張は、単にその属性が必須であるとほのめかしているだけです。属性が存在しない場合や空のときに、実際にバリデーションを失敗と判断するかどうかは、みなさん次第です。Note: An "implicit" extension only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.