Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You should look at creating your own form builder for customising the behaviour of <code>form_for</code>. You could do something that sets the class to the name of the validations defined on the attribute and have jQuery bind itself to the respective class names. Let's start with what the form builder might look like.</p> <pre><code>class ValidationFormBuilder &lt; ActionView::Helpers::FormBuilder def text_field(object_name, method, options = {}) options[:class] = object_name.class.validators_on(method).map do |k| # Eg: ActiveModel::Validations::PresenceValidator -&gt; presence k.to_s.slice(/[^:]+Validator$/).chomp('Validator').downcase end.join(' ') super(object_name, method, options) end end </code></pre> <p>You'll need to setup <code>form_for</code> to use the ValidationFormBuilder. </p> <pre><code>&lt;%= form_for @foo, :builder =&gt; ValidationFormBuilder do |f| %&gt; &lt;%= f.text_field :bar %&gt; &lt;% end %&gt; ... becomes something like &lt;form action="/foo" method="post"&gt; &lt;input type="text" class="presence" name="foo[bar]" id="foo_bar"&gt; &lt;/form&gt; </code></pre> <p>If you need more flexibility over the class names, you might want to create a hash that maps to the desired string.</p> <pre><code>class ValidationFormBuilder &lt; ActionView::Helpers::FormBuilder MAPPINGS = { ActiveModel::Validations::PresenceValidator =&gt; 'text' } def text_field(object_name, method, options = {}) options[:class] = object_name.class.validators_on(method).map do |k| MAPPINGS[k] end.join(' ') super(object_name, method, options) end end </code></pre> <p>You can see the complete list of validations included in Rails by peeking in <code>activemodel/lib/active_model/validations</code> of the Rails source code. I hope that's enough to get you started.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload