FormReflex is a light extension of optimism, leveraging stimulus_reflex.

FormReflex provides real time form validation on change, using the validations already provided on your model.


Please follow the setup instructions for optimism here

Usage for FormReflex is identical to the optimism usage, with 2 exceptions:

1) You must specify data-reflex="change->FormReflex#handle_change" on your form control


2) The model you want to validate must be initialized in session[:model]

For example:

def new
  @post =
  session[:model] = @post unless @stimulus_reflex

def set_post
  @post = Post.find(params[:id])
  session[:model] = @post unless @stimulus_reflex

All in all, pulling in Optimism's own example, it would look like this:

<%= form_with(model: session[:model]) do |form| %>
  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, data: { reflex: "change->FormReflex#handle_change" } %>
    <%= form.error_for :name %>

  <div class="field">
    <%= form.label :body %>
    <%= form.text_area :body, data: { reflex: "change->FormReflex#handle_change" } %>
    <%= form.error_for :body %>

  <div class="actions">
    <%= form.submit %>
<% end %>

You can also add models to an association easily with the add method. There's a corresponding delete method for removing models from an association. Simply add data-assocation="<name of association>" data-reflex="click->FormReflex#add"

<button type="button" data-association="post_details" data-reflex="click->FormReflex#add">
    Add Post Detail


Add this line to your application's Gemfile:

gem 'form-reflex'

And then execute:

$ bundle

Or install it yourself as:

$ gem install form-reflex


Contribution directions go here.


The gem is available as open source under the terms of the MIT License.