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

Faceted Search with Stimulus and Turbo Frames
10 December 2024

Harness the power of Stimulus and Turbo Frames to drive a simple but powerful faceted search solution

Turbo Frames - Markdown Preview
08 October 2024

Typeahead previews of markdown by simple Turbo Frame rerendering

Turbo Frames - Render Flash Messages Upon Form Submission
27 August 2024

Intercept form submission responses to render flash messages that are outside the originating Turbo Frame

Cookies
essential