我正在努力验证postal_code并使用不同的正则表达式,具体取决于country_code属性。我尝试了以下方法,但它不起作用:
class Venue < ActiveRecord::Base
...
attr_accessible :postal_code
attr_accessible :country_code
...
validates_presence_of :country_code
validates_length_of :country_code, :maximum => 2, :allow_nil => true
validates_inclusion_of :country_code, :in => %w( US CA AU GB )
validates_presence_of :postal_code
validates_length_of :postal_code, :maximum => 10, :allow_nil => true
validates_format_of :postal_code, :with => %r{^\d{4}$},
:message => "should be in the format 1111",
:allow_nil => true,
:if => :country_code == 'AU'
validates_format_of :postal_code, :with => %r{^\d{5}([\-]\d{4})?$},
:message => "should be in the format 11111 or 11111-1111",
:allow_nil => true,
:if => :country_code == 'US'
validates_format_of :postal_code, :with =>%r{^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$},
:message => "should be in the format A1A 1A1 (try making letters capitalized)",
:allow_nil => true,
:if => :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 => %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 => "invalid postal code (try making letters capitalized)",
:allow_nil => true,
:if => :country_code == 'GB'
我是完全不在此预订上,还是仅仅是:if
选项的格式?
答案 0 :(得分:5)
作为参考,:if =>
参数接受方法而不是条件,例如你可以
validate_presence_of :foo, :if => :country_is_gb?
def country_is_gb?
country_code == 'GB'
end
但如上所述,冗长或复杂的验证最好在单独的自定义验证器中完成。
答案 1 :(得分:3)
看一下这个截屏视频http://asciicasts.com/episodes/211-validations-in-rails-3 我认为它只是为您的邮政编码编写自定义验证函数的时间。