Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Scroll to validation errors in Laravel using Alpine.js

You know Laravel has this neat Blade directive called @error which you can use to display the validation error message for a given field. For instance, if you have a name field in your form and you want to display the validation error message for it, you can do it like so.

<label for="name">Name</label>
 
<input id="name"
    type="text"
    class="@error('name') is-invalid @enderror">

@error('name')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

As you can tell, the @error directive will display the validation error message for the name field if there’s any. But the problem with this is, that if the form is long and the validation error occurs in a place that is not in the viewport, the user will not be able to see the error message. And this is not a good user experience.

This can be fixed with the help of Alpine.js as described precisely in this tweet by Caleb Porzio.

So, what you can do is, you can add a x-init directive on the error message container and then call a method that will scroll the page to the error message container if the error message container is visible on the page.

@error('name')
    <div 
        class="alert alert-danger"
        x-init="$el.closest('form').scrollIntoView()"
    >
        {{ $message }}
    </div>
@enderror

The code in the x-init directive will scroll the page to the nearest form element if the error message container is visible on the page. This way, the user will be able to see all the validation errors even if they are not in the viewport.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?