• Hello, Visitor
  • Monday, February 17, 2025
Search Result
Home » Laravel » Livewire » Live Form Validation with Laravel Livewire

Live Form Validation with Laravel Livewire

Hello friends, today in this blog you’ll learn how to use live form validation in Laravel Livewire.

Here, Live Form Validation means that your form validation will update automatically. For example, if your input field is empty it will show a validation error & when you input any text the validation error will hide automatically. So, let's start

Video Tutorial:



Step 01: Add Form validation Error Messages and Models

Open your blade.php file and add the form variables & all validations error messages like the code given below,

<form action="" wire:submit.prevent='addPost'>
    <div class="form-group mb-3">
        <label for="">Post Title</label>
        <input type="text" name="" id="" wire:model='title' wire:keyup='generateSlug' class="form-control"
            placeholder="Enter title" />
            @error('title')
                <p class="text-danger" style="font-size: 12.5px;">{{ $message }}</p>
            @enderror
    </div>
    <div class="form-group mb-3">
        <label for="">Post Slug</label>
        <input type="text" name="" id="" wire:model='slug' class="form-control"
            placeholder="Enter slug" />
            @error('slug')
                <p class="text-danger" style="font-size: 12.5px;">{{ $message }}</p>
            @enderror
    </div>

    <div class="form-group mb-3">
        <label for="">Post Slug</label>
        <textarea name="" id="" wire:model='content' class="form-control" cols="30" rows="6" placeholder="Enter content"></textarea>
        @error('content')
                <p class="text-danger" style="font-size: 12.5px;">{{ $message }}</p>
        @enderror
    </div>

    <div class="form-group mb-3">
        <button type="submit" class="btn btn-primary btn-sm btn-block">Add Post</button>
    </div>
</form>


Step 02: Add Function & Variables in Class File

Open your component class file and add all variables as your form and add an updated() class inside the component class function. Here the updated() function is a laravel lifecycle hook, which will work in every livewire update

public $title, $slug, $content;

public function updated($fields)
{
    $this->validateOnly($fields, [
        'title' => 'required',
        'slug' =>'required',
        'content' =>'required',
    ]);
}

Also, add the addPost function to store the post with validation rules

public function addPost()
{
    $this->validate([
        'title' => 'required',
        'slug' =>'required',
        'content' =>'required',
    ]);

    $post = [
        'title' => $this->title,
        'slug' => $this->slug,
        'content' => $this->content,
    ];

    dd($post);
}


That's it, here the updated function will work as live validation changes.


Thanks for reading this post. Hope it will help you.


Leave a Reply

You must Login to add a comment