title: ActiveRecord validate url if it is present
body: <p>I would like to ensure that my class's <code>url</code> property has a value and if it does, it is valid:</p>
  
  <pre><code>class Entity &lt; ActiveRecord::Base
  
    validates :name, presence: true
    validates :url, presence: true, :format =&gt; {:with =&gt; URI.regexp}
  
  end
  </code></pre>
  
  <p>In the rails console:</p>
  
  <pre><code>&gt; e = Entity.new(name: 'foo')
  =&gt; #&lt;Entity id: nil, name: "foo", url: nil, created_at: nil, updated_at: nil&gt; 
  </code></pre>
  
  <p>Which results in two errors for the <code>url</code> attribute:</p>
  
  <pre><code>&gt; e.valid?
  =&gt; false
  
  &gt; e.errors
  =&gt; #&lt;ActiveModel::Errors:0x007fed9e324e28 @base=#&lt;Entity id: nil, name: "foo", url: nil, created_at: nil, updated_at: nil&gt;, @messages={:url=&gt;["can't be blank", "is invalid"]}&gt; 
  </code></pre>
  
  <p>Ideally, a <code>nil</code> <code>url</code> would produce a single error (i.e. <code>can't be blank</code>).</p>
  
  <p>As such, I've change the <code>validates</code> rule:</p>
  
  <pre><code>validates :url, presence: true, :with =&gt; Proc.new { URI.regexp if :url? }
  </code></pre>
  
  <p>I can't get the syntax to work, however.  What am I missing?</p>