Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>[Update]</strong> Jan/2013 to Rails 3.2.x - update syntax; add spec</p> <p>Inspired by new <a href="http://lindsaar.net/2010/1/31/validates_rails_3_awesome_is_true" rel="noreferrer">validation</a> methods in Rails 3.0 I'm adding this tiny Validator. I call it <code>ReduceValidator</code>.</p> <p><em><code>lib/reduce_validator.rb</code></em>:</p> <pre><code># show only one error message per field # class ReduceValidator &lt; ActiveModel::EachValidator def validate_each(record, attribute, value) return until record.errors.messages.has_key?(attribute) record.errors[attribute].slice!(-1) until record.errors[attribute].size &lt;= 1 end end </code></pre> <p>My Model looking like - notice the <strong><code>:reduce =&gt; true</code></strong>:</p> <pre><code>validates :title, :presence =&gt; true, :inclusion =&gt; { :in =&gt; %w[ Mr Mrs ] }, :reduce =&gt; true validates :firstname, :presence =&gt; true, :length =&gt; { :within =&gt; 2..50 }, :format =&gt; { :without =&gt; /^\D{1}[.]/i }, :reduce =&gt; true validates :lastname, :presence =&gt; true, :length =&gt; { :within =&gt; 2..50 }, :format =&gt; { :without =&gt; /^\D{1}[.]/i }, :reduce =&gt; true </code></pre> <p>Works like a charm in my current Rails Project. The advantageous is, i've put the validator only on a few fields not all.</p> <p><em><code>spec/lib/reduce_validator_spec.rb</code></em>:</p> <pre><code>require 'spec_helper' describe ReduceValidator do let(:reduce_validator) { ReduceValidator.new({ :attributes =&gt; {} }) } let(:item) { mock_model("Item") } subject { item } before(:each) do item.errors.add(:name, "message one") item.errors.add(:name, "message two") end it { should have(2).error_on(:name) } it "should reduce error messages" do reduce_validator.validate_each(item, :name, '') should have(1).error_on(:name) end end </code></pre>
 

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