Note that there are some explanatory texts on larger screens.

plurals
  1. POConditional validation on model dependent on value of model attribute
    primarykey
    data
    text
    <p>I'm struggling with validating a postal_code and using a different regex depending on what the country_code attribute is. I tried the following, but it does not work:</p> <pre><code>class Venue &lt; ActiveRecord::Base ... attr_accessible :postal_code attr_accessible :country_code ... validates_presence_of :country_code validates_length_of :country_code, :maximum =&gt; 2, :allow_nil =&gt; true validates_inclusion_of :country_code, :in =&gt; %w( US CA AU GB ) validates_presence_of :postal_code validates_length_of :postal_code, :maximum =&gt; 10, :allow_nil =&gt; true validates_format_of :postal_code, :with =&gt; %r{^\d{4}$}, :message =&gt; "should be in the format 1111", :allow_nil =&gt; true, :if =&gt; :country_code == 'AU' validates_format_of :postal_code, :with =&gt; %r{^\d{5}([\-]\d{4})?$}, :message =&gt; "should be in the format 11111 or 11111-1111", :allow_nil =&gt; true, :if =&gt; :country_code == 'US' validates_format_of :postal_code, :with =&gt;%r{^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$}, :message =&gt; "should be in the format A1A 1A1 (try making letters capitalized)", :allow_nil =&gt; true, :if =&gt; :country_code == 'CA' # ridculously long (but thorough) regex courtesy of Wikipedia (http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom) validates_format_of :postal_code, :with =&gt; %r{^(GIR 0AA)|(((A[BL]|B[ABDHLNRSTX]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]?|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTY]?|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)[1-9]?[0-9]|((E|N|NW|SE|SW|W)1|EC[1-4]|WC[12])[A-HJKMNPR-Y]|(SW|W)([2-9]|[1-9][0-9])|EC[1-9][0-9]) [0-9][ABD-HJLNP-UW-Z]{2})$}, :message =&gt; "invalid postal code (try making letters capitalized)", :allow_nil =&gt; true, :if =&gt; :country_code == 'GB' </code></pre> <p>Am I totally off the reservation on this, or is it just the format of the <code>:if</code> options that are hosed up?</p>
    singulars
    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.
 

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