Turbo Frames - Modals with Validation

Handle modal dialogs with Turbo Frames and minimal additional JavaScript

View Solution on Patreon
Turbo Frames - Modals with Validation

Premise

Modal dialogs have been haunting me (and I’m sure countless others) since I started developing for the web in 2004. Since the <dialog> element has become supported in all major modern browsers, a lot of the boilerplate has been standardized (e.g. by providing a dialog form method to capture and provide return values). Turbo’s idiosyncrasies, however, necessitate us to take a closer look at how to handle forms inside <dialog>s.

Starting Point

I literally copied the “favorite animals” example from the MDN docs as a starting point. Clicking on “Update favorite animal” opens a dialog with a select box and a submit button. Selecting a new favorite animal works fine, but if you leave the select box empty, the dialog closes without showing any error:

A modal dialog unable to handle validation errors

Challenge

First of all, the Stackblitz backend mimicks exactly the way a Turbo powered Rails app would respond to a form action:

https://stackblitz.com/edit/turbo-frames-modals-validation?file=index.js%3AL28

  • if valid, respond with a 303 pointing to the redirect location
  • if invalid, respond with a 422 and include the error messages in the response.

Now, use a Turbo Frame to wrap the form and capture the validation errors:

https://stackblitz.com/edit/turbo-frames-modals-validation?file=index.html%3AL42

Caveats

Just wrapping the form with a Turbo Frame will yield another issue, this time with the valid response. You’ll need to add some custom JavaScript to handle it.

More from

Turbo Frames - Loading Spinner
20 January 2026

Display a loading spinner while a Turbo Frame is `busy` fetching content asynchronously

Turbo Frames - Typeahead Validation
20 October 2025

Use "preflight" requests to validate a form before submitting it

Turbo Frames - Swiper with Autoplay and View Transitions
14 January 2025

Create an autoplaying swiper using view transitions and Turbo Frames

Cookies
essential