title: Rails model attribute allow nil but validate when not
body: <p>I want to validate an input box value in two cases:</p>
  
  <ol>
  <li>If nil? then save successfully, no errors</li>
  <li>If not nil? then validate its format</li>
  </ol>
  
  <p>I have a simple line here:</p>
  
  <pre><code>validates :ip_addr, format: { with: Regexp.union(Resolv::IPv4::Regex)}
  </code></pre>
  
  <p>This will work in all cases but won't allow a nil/empty value as it throws an exception. But:</p>
  
  <pre><code>validates :ip_addr, format: { with: Regexp.union(Resolv::IPv4::Regex)}, allow_nil: true
  </code></pre>
  
  <p>and </p>
  
  <pre><code>validates :ip_addr, format: { with: Regexp.union(Resolv::IPv4::Regex)}, allow_blank: true
  </code></pre>
  
  <p>Will allow nil/empty values but If the input is invalid e.g. "33@@@#$" then it returns "true".</p>
  
  <p>How could I include both cases ? Is that possible ? </p>
  
  <p>EDIT: It seems that <code>Regexp.union(Resolv::IPv4::Regex).match("something")</code> returns nil so If the validation works the same way, it will return nil in wrong values and <code>allow_nil: true</code> will allow them to be persisted like this. </p>