Skip to content

Bootstrap Modal Validations

David Kimura edited this page Oct 20, 2016 · 4 revisions

In this scenario, the following versions are being used. Based on your application and dependencies, the steps may vary.

  • rails 5.0.0.1
  • bootstrap-sass 3.3.7
  • simple_form 3.3.1

The problem with client side validations when using a bootstrap modal is that the validations are not triggered since the form fields are not visible. To get around this issue, you can add a listener for when the bootstrap modal is displayed and then enable validations on the form within the bootstrap modal.

Since we are using validate: true within our form declaration, this will yield something like this:

<%= simple_form_for @something, html: {class: 'form-horizontal' }, validate: true do |f| %>
  ...
<% end %>

will produce

<form data-validate="true" ...>

We can create a universal enabler for our modals. We will check the class modal for whenever shown.bs.modal is triggered and call enableClientSideValidations() on form[data-validate].

$ ->
  $('.modal').on 'shown.bs.modal', ->
    $('form[data-validate]').enableClientSideValidations()

or

$('.modal').on('shown.bs.modal', function() {
  $('form[data-validate]').enableClientSideValidations();
});

I prefer this method as it is a one time script that would take into account any bootstrap modal which has a form and validate: true set within the form declaration. While it does increase the overall DOM processing, I feel that it is a negligible amount.

Clone this wiki locally