Readouble

Livewire v3 バリデーション

バリデーション

Livewire は、ユーザーの入力を検証し、フィードバックを提供するプロセスを可能な限り快適にすることを目指しています。Laravel のバリデーション機能を基盤とすることで、Livewire は既存の知識を活用しつつ、リアルタイムバリデーションのような堅牢な追加機能も提供します。Livewire aims to make validating a user's input and giving them feedback as pleasant as possible. By building on top of Laravel's validation features, Livewire leverages your existing knowledge while also providing you with robust, additional features like real-time validation.

以下は、Livewire での最も基本的なバリデーションワークフローを示す CreatePost コンポーネントの例です。Here's an example CreatePost component that demonstrates the most basic validation workflow in Livewire:

<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
	public $title = '';

    public $content = '';

    public function save()
    {
        $validated = $this->validate([ // [tl! highlight:3]
			'title' => 'required|min:3',
			'content' => 'required|min:3',
        ]);

		Post::create($validated);

		return redirect()->to('/posts');
    }

    public function render()
    {
        return view('livewire.create-post');
    }
}
<form wire:submit="save">
	<input type="text" wire:model="title">
    <div>@error('title') {{ $message }} @enderror</div>

	<textarea wire:model="content"></textarea>
    <div>@error('content') {{ $message }} @enderror</div>

	<button type="submit">Save</button>
</form>

ご覧のとおり、Livewire はコンポーネントのプロパティを検証するために呼び出すことができる validate() メソッドを提供します。このメソッドは、検証済みのデータセットを返し、データベースに安全に挿入できます。As you can see, Livewire provides a validate() method that you can call to validate your component's properties. It returns the validated set of data that you can then safely insert into the database.

フロントエンドでは、Laravel の既存の Blade ディレクティブを使用して、検証メッセージをユーザーに表示できます。On the frontend, you can use Laravel's existing Blade directives to show validation messages to your users.

詳細については、Blade でのバリデーションエラーのレンダリングに関する Laravel のドキュメントを参照してください。For more information, see Laravel's documentation on rendering validation errors in Blade[https://laravel.com/docs/blade#validation-errors].

属性の検証Validate attributes

コンポーネントの検証ルールをプロパティと直接配置したい場合は、Livewire の #[Validate] 属性を使用できます。If you prefer to co-locate your component's validation rules with the properties directly, you can use Livewire's #[Validate] attribute.

#[Validate] を使用して検証ルールをプロパティに関連付けることにより、Livewire は各更新の前にプロパティの検証ルールを自動的に実行します。ただし、更新されていないプロパティも検証されるように、データベースにデータを永続化する前に、$this->validate() を実行する必要があります。By associating validation rules with properties using #[Validate], Livewire will automatically run the properties validation rules before each update. However, you should still run $this->validate() before persisting data to a database so that properties that haven't been updated are also validated.

use Livewire\Attributes\Validate;
use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
    #[Validate('required|min:3')] // [tl! highlight]
	public $title = '';

    #[Validate('required|min:3')] // [tl! highlight]
    public $content = '';

    public function save()
    {
        $this->validate();

		Post::create([
            'title' => $this->title,
            'content' => $this->content,
		]);

		return redirect()->to('/posts');
    }

    // ...
}

lightbulb Info: Validate 属性は Rule オブジェクトをサポートしていません PHP 属性は、プレーンな文字列や配列などの特定の構文に制限されています。Laravel の Rule オブジェクト (Rule::exists(...)) のようなランタイム構文を使用したい場合は、代わりにコンポーネントで rules() メソッドを定義 してください。[!info] Validate attributes don't support Rule objects PHP Attributes are restricted to certain syntaxes like plain strings and arrays. If you find yourself wanting to use run-time syntaxes like Laravel's Rule objects (Rule::exists(...)) you should instead define a rules() method[#defining-a-rules-method] in your component.

詳細については、Livewire での Laravel Rule オブジェクトの使用に関するドキュメントを参照してください。Learn more in the documentation on using Laravel Rule objects with Livewire[#using-laravel-rule-objects].

プロパティが検証されるタイミングをより細かく制御したい場合は、#[Validate] 属性に onUpdate: false パラメータを渡すことができます。これにより、自動検証が無効になり、代わりに $this->validate() メソッドを使用してプロパティを手動で検証することが想定されます。If you prefer more control over when the properties are validated, you can pass a onUpdate: false parameter to the #[Validate] attribute. This will disable any automatic validation and instead assume you want to manually validate the properties using the $this->validate() method:

use Livewire\Attributes\Validate;
use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
    #[Validate('required|min:3', onUpdate: false)]
	public $title = '';

    #[Validate('required|min:3', onUpdate: false)]
    public $content = '';

    public function save()
    {
        $validated = $this->validate();

		Post::create($validated);

		return redirect()->to('/posts');
    }

    // ...
}

カスタム属性名Custom attribute name

検証メッセージに挿入される属性名をカスタマイズしたい場合は、as: パラメータを使用できます。If you wish to customize the attribute name injected into the validation message, you may do so using the as: parameter:

use Livewire\Attributes\Validate;

#[Validate('required', as: 'date of birth')]
public $dob;

上記のコードスニペットで検証が失敗した場合、Laravel は検証メッセージのフィールド名として "dob" の代わりに "date of birth" を使用します。生成されるメッセージは "The date of birth field is required" になり、"The dob field is required" にはなりません。When validation fails in the above snippet, Laravel will use "date of birth" instead of "dob" as the name of the field in the validation message. The generated message will be "The date of birth field is required" instead of "The dob field is required".

カスタム検証メッセージCustom validation message

Laravel の検証メッセージをバイパスして、独自のメッセージに置き換えるには、#[Validate] 属性で message: パラメータを使用します。To bypass Laravel's validation message and replace it with your own, you can use the message: parameter in the #[Validate] attribute:

use Livewire\Attributes\Validate;

#[Validate('required', message: 'Please provide a post title')]
public $title;

これで、このプロパティの検証が失敗すると、メッセージは "The title field is required" ではなく "Please provide a post title" になります。Now, when the validation fails for this property, the message will be "Please provide a post title" instead of "The title field is required".

異なるルールに異なるメッセージを追加したい場合は、複数の #[Validate] 属性を簡単に指定できます。If you wish to add different messages for different rules, you can simply provide multiple #[Validate] attributes:

#[Validate('required', message: 'Please provide a post title')]
#[Validate('min:3', message: 'This title is too short')]
public $title;

ローカライゼーションのオプトアウトOpting out of localization

デフォルトでは、Livewire のルールメッセージと属性は、Laravel の翻訳ヘルパ trans() を使用してローカライズされます。By default, Livewire rule messages and attributes are localized using Laravel's translate helper: trans().

#[Validate] 属性に translate: false パラメータを渡すことで、ローカライゼーションをオプトアウトできます。You can opt-out of localization by passing the translate: false parameter to the #[Validate] attribute:

#[Validate('required', message: 'Please provide a post title', translate: false)]
public $title;

カスタムキーCustom key

#[Validate] 属性を使用してプロパティに直接検証ルールを適用する場合、Livewire は検証キーがプロパティ自体の名前であると想定します。ただし、検証キーをカスタマイズしたい場合があります。When applying validation rules directly to a property using the #[Validate] attribute, Livewire assumes the validation key should be the name of the property itself. However, there are times when you may want to customize the validation key.

たとえば、配列プロパティとその子に対して個別の検証ルールを指定したい場合があります。この場合、検証ルールを #[Validate] 属性の最初の引数として渡す代わりに、キーと値のペアの配列を渡すことができます。For example, you might want to provide separate validation rules for an array property and its children. In this case, instead of passing a validation rule as the first argument to the #[Validate] attribute, you can pass an array of key-value pairs instead:

#[Validate([
    'todos' => 'required',
    'todos.*' => [
        'required',
        'min:3',
        new Uppercase,
    ],
])]
public $todos = [];

これで、ユーザーが $todos を更新するか、validate() メソッドが呼び出されると、これらの検証ルールが両方とも適用されます。Now, when a user updates $todos, or the validate() method is called, both of these validation rules will be applied.

フォームオブジェクトForm objects

Livewire コンポーネントに追加されるプロパティと検証ルールが増えるにつれて、過密に感じ始めることがあります。この問題を軽減し、コードの再利用に役立つ抽象化を提供するために、Livewire の フォームオブジェクト を使用して、プロパティと検証ルールを保存できます。As more properties and validation rules are added to a Livewire component, it can begin to feel too crowded. To alleviate this pain and also provide a helpful abstraction for code reuse, you can use Livewire's Form Objects to store your properties and validation rules.

以下は同じ CreatePost の例ですが、プロパティとルールは PostForm という専用のフォームオブジェクトに抽出されています。Below is the same CreatePost example, but now the properties and rules have been extracted to a dedicated form object named PostForm:

<?php

namespace App\Livewire\Forms;

use Livewire\Attributes\Validate;
use Livewire\Form;

class PostForm extends Form
{
    #[Validate('required|min:3')]
	public $title = '';

    #[Validate('required|min:3')]
    public $content = '';
}

上記の PostForm は、CreatePost コンポーネントのプロパティとして定義できるようになりました。The PostForm above can now be defined as a property on the CreatePost component:

<?php

namespace App\Livewire;

use App\Livewire\Forms\PostForm;
use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
    public PostForm $form;

    public function save()
    {
		Post::create(
    		$this->form->all()
    	);

		return redirect()->to('/posts');
    }

    // ...
}

ご覧のとおり、各プロパティを個別にリストする代わりに、フォームオブジェクトの ->all() メソッドを使用してすべてのプロパティ値を取得できます。As you can see, instead of listing out each property individually, we can retrieve all the property values using the ->all() method on the form object.

また、テンプレートでプロパティ名を参照する場合は、各インスタンスの前に form. を付ける必要があります。Also, when referencing the property names in the template, you must prepend form. to each instance:

<form wire:submit="save">
	<input type="text" wire:model="form.title">
    <div>@error('form.title') {{ $message }} @enderror</div>

	<textarea wire:model="form.content"></textarea>
    <div>@error('form.content') {{ $message }} @enderror</div>

	<button type="submit">Save</button>
</form>

フォームオブジェクトを使用する場合、#[Validate] 属性の検証はプロパティが更新されるたびに実行されます。ただし、属性で onUpdate: false を指定してこの動作を無効にした場合は、$this->form->validate() を使用してフォームオブジェクトの検証を手動で実行できます。When using form objects, #[Validate] attribute validation will be run every time a property is updated. However, if you disable this behavior by specifying onUpdate: false on the attribute, you can manually run a form object's validation using $this->form->validate():

public function save()
{
    Post::create(
        $this->form->validate()
    );

    return redirect()->to('/posts');
}

フォームオブジェクトは、ほとんどの大規模なデータセットと、さらに強力にするさまざまな追加機能に役立つ抽象化です。詳細については、包括的なフォームオブジェクトのドキュメントをご覧ください。Form objects are a useful abstraction for most larger datasets and a variety of additional features that make them even more powerful. For more information, check out the comprehensive form object documentation[/docs/forms#extracting-a-form-object].

リアルタイム検証Real-time validation

リアルタイム検証とは、フォームの送信を待つのではなく、ユーザーがフォームに入力するときに入力を検証するために使用される用語です。Real-time validation is the term used for when you validate a user's input as they fill out a form rather than waiting for the form submission.

Livewire プロパティで直接 #[Validate] 属性を使用すると、ネットワークリクエストが送信されてサーバ上のプロパティの値を更新するたびに、指定された検証ルールが適用されます。By using #[Validate] attributes directly on Livewire properties, any time a network request is sent to update a property's value on the server, the provided validation rules will be applied.

これは、特定の入力でユーザーにリアルタイム検証エクスペリエンスを提供するために、追加のバックエンド作業は必要ないことを意味します。必要なのは、wire:model.live または wire:model.blur を使用して、フィールドが入力されたときにネットワークリクエストをトリガーするように Livewire に指示することだけです。This means to provide a real-time validation experience for your users on a specific input, no extra backend work is required. The only thing that is required is using wire:model.live or wire:model.blur to instruct Livewire to trigger network requests as the fields are filled out.

以下の例では、wire:model.blur がテキスト入力に追加されています。これで、ユーザーがフィールドに入力してからフィールドからタブ移動またはクリックすると、更新された値でネットワークリクエストがトリガーされ、検証ルールが実行されます。In the below example, wire:model.blur has been added to the text input. Now, when a user types in the field and then tabs or clicks away from the field, a network request will be triggered with the updated value and the validation rules will run:

<form wire:submit="save">
    <input type="text" wire:model.blur="title">

    <!-- -->
</form>

#[Validate] 属性の代わりに rules() メソッドを使用してプロパティの検証ルールを宣言する場合でも、パラメータなしで #[Validate] 属性を含めることで、リアルタイム検証の動作を維持できます。If you are using a rules() method to declare your validation rules for a property instead of the #[Validate] attribute, you can still include a #[Validate] attribute with no parameters to retain the real-time validating behavior:

use Livewire\Attributes\Validate;
use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
    #[Validate] // [tl! highlight]
	public $title = '';

    public $content = '';

    protected function rules()
    {
        return [
            'title' => 'required|min:5',
            'content' => 'required|min:5',
        ];
    }

    public function save()
    {
        $validated = $this->validate();

		Post::create($validated);

		return redirect()->to('/posts');
    }

さて、上記の例では、#[Validate]が空であっても、プロパティが更新されるたびに、Livewireはrules()で提供されるフィールドのバリデーションを実行するように指示します。Now, in the above example, even though #[Validate] is empty, it will tell Livewire to run the fields validation provided by rules() everytime the property is updated.

エラーメッセージのカスタマイズCustomizing error messages

Laravelは、初期設定で、$titleプロパティにrequiredルールが設定されている場合、「The title field is required.(タイトルフィールドは必須です)」のような適切なバリデーションメッセージを提供します。Out-of-the-box, Laravel provides sensible validation messages like "The title field is required." if the $title property has the required rule attached to it.

ただし、アプリケーションやユーザーに合わせて、これらのエラーメッセージの言語をカスタマイズする必要がある場合があります。However, you may need to customize the language of these error messages to better suite your application and its users.

カスタム属性名Custom attribute names

検証するプロパティの名前が、ユーザーに表示するのに適していない場合があります。たとえば、アプリに「生年月日」を表すdobという名前のデータベースフィールドがある場合、「The dob field is required(dobフィールドは必須です)」ではなく、「The date of birth field is required(生年月日フィールドは必須です)」とユーザーに表示したい場合があります。Sometimes the property you are validating has a name that isn't suited for displaying to users. For example, if you have a database field in your app named dob that stands for "Date of birth", you would want to show your users "The date of birth field is required" instead of "The dob field is required".

Livewireでは、as:パラメータを使用して、プロパティの代替名を指定できます。Livewire allows you to specify an alternative name for a property using the as: parameter:

use Livewire\Attributes\Validate;

#[Validate('required', as: 'date of birth')]
public $dob = '';

これで、requiredバリデーションルールが失敗した場合、エラーメッセージは「The dob field is required.(dobフィールドは必須です)」ではなく、「The date of birth field is required.(生年月日フィールドは必須です)」と表示されます。Now, if the required validation rule fails, the error message will state "The date of birth field is required." instead of "The dob field is required.".

カスタムメッセージCustom messages

プロパティ名のカスタマイズだけでは不十分な場合は、message:パラメータを使用して、バリデーションメッセージ全体をカスタマイズできます。If customizing the property name isn't enough, you can customize the entire validation message using the message: parameter:

use Livewire\Attributes\Validate;

#[Validate('required', message: 'Please fill out your date of birth.')]
public $dob = '';

メッセージをカスタマイズするルールが複数ある場合は、次のように、それぞれに完全に独立した#[Validate]属性を使用することをお勧めします。If you have multiple rules to customize the message for, it is recommended that you use entirely separate #[Validate] attributes for each, like so:

use Livewire\Attributes\Validate;

#[Validate('required', message: 'Please enter a title.')]
#[Validate('min:5', message: 'Your title is too short.')]
public $title = '';

#[Validate]属性の配列構文を使用する場合は、次のようにカスタム属性とメッセージを指定できます。If you want to use the #[Validate] attribute's array syntax instead, you can specify custom attributes and messages like so:

use Livewire\Attributes\Validate;

#[Validate([
    'titles' => 'required',
    'titles.*' => 'required|min:5',
], message: [
    'required' => 'The :attribute is missing.',
    'titles.required' => 'The :attribute are missing.',
    'min' => 'The :attribute is too short.',
], attribute: [
    'titles.*' => 'title',
])]
public $titles = [];

rules()メソッドの定義Defining a rules() method

Livewireの#[Validate]属性の代替として、コンポーネントにrules()という名前のメソッドを定義し、フィールドと対応するバリデーションルールのリストを返すことができます。これは、PHP Attributesでサポートされていないランタイム構文(たとえば、LaravelのRule::password()のようなルールオブジェクト)を使用しようとしている場合に役立ちます。As an alternative to Livewire's #[Validate] attributes, you can define a method in your component called rules() and return a list of fields and corresponding validation rules. This can be helpful if you are trying to use run-time syntaxes that aren't supported in PHP Attributes, for example, Laravel rule objects like Rule::password().

これらのルールは、コンポーネント内で$this->validate()を実行するときに適用されます。messages()関数とvalidationAttributes()関数も定義できます。These rules will then be applied when you run $this->validate() inside the component. You also can define the messages() and validationAttributes() functions.

次に例を示します。Here's an example:

use Livewire\Component;
use App\Models\Post;
use Illuminate\Validation\Rule;

class CreatePost extends Component
{
	public $title = '';

    public $content = '';

    protected function rules() // [tl! highlight:6]
    {
        return [
            'title' => Rule::exists('posts', 'title'),
            'content' => 'required|min:3',
        ];
    }

    protected function messages() // [tl! highlight:6]
    {
        return [
            'content.required' => 'The :attribute are missing.',
            'content.min' => 'The :attribute is too short.',
        ];
    }

    protected function validationAttributes() // [tl! highlight:6]
    {
        return [
            'content' => 'description',
        ];
    }

    public function save()
    {
        $this->validate();

		Post::create([
            'title' => $this->title,
            'content' => $this->content,
		]);

		return redirect()->to('/posts');
    }

    // ...
}

warning Warning! rules()メソッドはデータ更新時にバリデーションを行いません rules()メソッドを使用してルールを定義する場合、Livewireは$this->validate()を実行するときに、これらのバリデーションルールのみを使用してプロパティを検証します。これは、wire:modelなどを介してフィールドが更新されるたびに適用される標準の#[Validate]属性とは異なります。プロパティが更新されるたびにこれらのバリデーションルールを適用するには、追加のパラメータなしで#[Validate]を使用できます。[!warning] The rules() method doesn't validate on data updates When defining rules via the rules() method, Livewire will ONLY use these validation rules to validate properties when you run $this->validate(). This is different than standard #[Validate] attributes which are applied every time a field is updated via something like wire:model. To apply these validation rules to a property every time it's updated, you can still use #[Validate] with no extra parameters.

warning Warning! Livewireのメカニズムとの競合を避けてください Livewireのバリデーションユーティリティを使用する際、コンポーネントにrulesmessagesvalidationAttributesvalidationCustomValuesという名前のプロパティまたはメソッドを含めないでください。ただし、バリデーションプロセスをカスタマイズする場合は除きます。そうしないと、Livewireのメカニズムと競合します。[!warning] Don't conflict with Livewire's mechanisms While using Livewire's validation utilities, your component should not have properties or methods named rules, messages, validationAttributes or validationCustomValues, unless you're customizing the validation process. Otherwise, those will conflict with Livewire's mechanisms.

Laravel Ruleオブジェクトの使用Using Laravel Rule objects

LaravelのRuleオブジェクトは、フォームに高度なバリデーション動作を追加するための非常に強力な方法です。Laravel Rule objects are an extremely powerful way to add advanced validation behavior to your forms.

次に、Livewireのrules()メソッドと組み合わせてRuleオブジェクトを使用して、より洗練されたバリデーションを実現する例を示します。Here is an example of using Rule objects in conjunction with Livewire's rules() method to achieve more sophisticated validation:

<?php

namespace App\Livewire;

use Illuminate\Validation\Rule;
use App\Models\Post;
use Livewire\Form;

class UpdatePost extends Form
{
    public ?Post $post;

    public $title = '';

    public $content = '';

    protected function rules()
    {
        return [
            'title' => [
                'required',
                Rule::unique('posts')->ignore($this->post), // [tl! highlight]
            ],
            'content' => 'required|min:5',
        ];
    }

    public function mount()
    {
        $this->title = $this->post->title;
        $this->content = $this->post->content;
    }

    public function update()
    {
        $this->validate(); // [tl! highlight]

        $this->post->update($this->all());

        $this->reset();
    }

    // ...
}

バリデーションエラーの手動制御Manually controlling validation errors

Livewireのバリデーションユーティリティは、ほとんどの一般的なバリデーションシナリオを処理できます。ただし、コンポーネント内のバリデーションメッセージを完全に制御したい場合があります。Livewire's validation utilities should handle the most common validation scenarios; however, there are times when you may want full control over the validation messages in your component.

以下は、Livewireコンポーネントでバリデーションエラーを操作するために使用できるすべてのメソッドです。Below are all the available methods for manipulating the validation errors in your Livewire component:

MethodMethod DescriptionDescription
$this->addError([key], [message])$this->addError([key], [message]) エラーバッグにバリデーションメッセージを手動で追加しますManually add a validation message to the error bag
$this->resetValidation([?key])$this->resetValidation([?key]) 指定されたキーのバリデーションエラーをリセットするか、キーが指定されていない場合はすべてのエラーをリセットしますReset the validation errors for the provided key, or reset all errors if no key is supplied
$this->getErrorBag()$this->getErrorBag() Livewireコンポーネントで使用されている基盤となるLaravelエラーバッグを取得しますRetrieve the underlying Laravel error bag used in the Livewire component

lightbulb Info: Form Objectsでの$this->addError()の使用 フォームオブジェクト内で$this->addErrorを使用してエラーを手動で追加すると、キーには、フォームが親コンポーネントで割り当てられているプロパティの名前が自動的にプレフィックスとして付加されます。たとえば、コンポーネントでフォームを$dataという名前のプロパティに割り当てる場合、キーはdata.keyになります。[!info] Using $this->addError() with Form Objects When manually adding errors using $this->addError inside of a form object the key will automatically be prefixed with the name of the property the form is assigned to in the parent component. For example, if in your Component you assign the form to a property called $data, key will become data.key.

ValidatorインスタンスへのアクセスAccessing the validator instance

Livewireがvalidate()メソッド内で内部的に使用するValidatorインスタンスにアクセスしたい場合があります。これは、withValidatorメソッドを使用して可能です。提供するクロージャは、完全に構築されたvalidatorを引数として受け取り、バリデーションルールが実際に評価される前に、そのメソッドを呼び出すことができます。Sometimes you may want to access the Validator instance that Livewire uses internally in the validate() method. This is possible using the withValidator method. The closure you provide receives the fully constructed validator as an argument, allowing you to call any of its methods before the validation rules are actually evaluated.

以下は、Livewireの内部validatorをインターセプトして、手動で条件をチェックし、追加のバリデーションメッセージを追加する例です。Below is an example of intercepting Livewire's internal validator to manually check a condition and add an additional validation message:

use Livewire\Attributes\Validate;
use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
    #[Validate('required|min:3')]
	public $title = '';

    #[Validate('required|min:3')]
    public $content = '';

    public function boot()
    {
        $this->withValidator(function ($validator) {
            $validator->after(function ($validator) {
                if (str($this->title)->startsWith('"')) {
                    $validator->errors()->add('title', 'Titles cannot start with quotations');
                }
            });
        });
    }

    public function save()
    {
		Post::create($this->all());

		return redirect()->to('/posts');
    }

    // ...
}

カスタムバリデーターの使用Using custom validators

Livewireで独自のバリデーションシステムを使用したい場合は、問題ありません。Livewireは、コンポーネント内でスローされたすべてのValidationException例外をキャッチし、Livewire独自のvalidate()メソッドを使用しているかのように、エラーをビューに提供します。If you wish to use your own validation system in Livewire, that isn't a problem. Livewire will catch any ValidationException exceptions thrown inside of components and provide the errors to the view just as if you were using Livewire's own validate() method.

以下はCreatePostコンポーネントの例ですが、Livewireのバリデーション機能を使用する代わりに、完全にカスタムのバリデーターが作成され、コンポーネントプロパティに適用されています。Below is an example of the CreatePost component, but instead of using Livewire's validation features, a completely custom validator is being created and applied to the component properties:

use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
	public $title = '';

    public $content = '';

    public function save()
    {
        $validated = Validator::make(
            // Data to validate... (検証するデータ)
            ['title' => $this->title, 'content' => $this->content],

            // Validation rules to apply... (適用するバリデーションルール)
            ['title' => 'required|min:3', 'content' => 'required|min:3'],

            // Custom validation messages... (カスタムバリデーションメッセージ)
            ['required' => 'The :attribute field is required'],
         )->validate();

		Post::create($validated);

		return redirect()->to('/posts');
    }

    // ...
}

バリデーションのテストTesting validation

Livewireは、assertHasErrors()メソッドなど、バリデーションシナリオに役立つテストユーティリティを提供します。Livewire provides useful testing utilities for validation scenarios, such as the assertHasErrors() method.

以下は、titleプロパティに入力が設定されていない場合にバリデーションエラーがスローされることを確認する基本的なテストケースです。Below is a basic test case that ensures validation errors are thrown if no input is set for the title property:

<?php

namespace Tests\Feature\Livewire;

use App\Livewire\CreatePost;
use Livewire\Livewire;
use Tests\TestCase;

class CreatePostTest extends TestCase
{
    public function test_cant_create_post_without_title()
    {
        Livewire::test(CreatePost::class)
            ->set('content', 'Sample content...')
            ->call('save')
            ->assertHasErrors('title');
    }
}

エラーの有無をテストすることに加え、assertHasErrors メソッドの第二引数に検証対象のルールを渡すことで、アサーションを特定のルールに絞り込むことができます。In addition to testing the presence of errors, assertHasErrors allows you to also narrow down the assertion to specific rules by passing the rules to assert against as the second argument to the method:

public function test_cant_create_post_with_title_shorter_than_3_characters()
{
    Livewire::test(CreatePost::class)
        ->set('title', 'Sa')
        ->set('content', 'Sample content...')
        ->call('save')
        ->assertHasErrors(['title' => ['min:3']]);
}

複数のプロパティに対して同時にバリデーションエラーの有無をアサートすることもできます。You can also assert the presence of validation errors for multiple properties at the same time:

public function test_cant_create_post_without_title_and_content()
{
    Livewire::test(CreatePost::class)
        ->call('save')
        ->assertHasErrors(['title', 'content']);
}

Livewire が提供するその他のテストユーティリティの詳細については、testing documentation を参照してください。For more information on other testing utilities provided by Livewire, check out the testing documentation[/docs/testing].

非推奨の [#Rule] 属性Deprecated [#Rule] attribute

Livewire v3 が最初にリリースされたとき、バリデーション属性 (#[Rule]) には "Validate" ではなく "Rule" という用語が使用されていました。When Livewire v3 first launched, it used the term "Rule" instead of "Validate" for it's validation attributes (#[Rule]).

Laravel のルールオブジェクトとの命名の競合のため、これはその後 #[Validate] に変更されました。どちらも Livewire v3 でサポートされていますが、最新の状態を維持するために、#[Rule] のすべての出現箇所を #[Validate] に変更することをお勧めします。Because of naming conflicts with Laravel rule objects, this has since been changed to #[Validate]. Both are supported in Livewire v3, however it is recommended that you change all occurrences of #[Rule] with #[Validate] to stay current.

章選択

パッケージ

設定

バージョン変更
linkv3 linkv2
明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
OS表示
全OS表示
macOSのみ表示
windowsのみ表示
linuxのみ表示
JSフレームワーク
両フレームワーク
Reactのみ表示
Vueのみ表示
JSのみ表示

(JSが存在しない場合は、他を全表示)

和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作