许多国家的邮政编码的Rails条件验证

时间:2012-03-20 19:44:21

标签: ruby-on-rails validation model conditional

我需要在美国和加拿大对邮政编码进行模型级验证。这段代码让我心疼:

zip_regex_usa = %r{\d{5}(-\d{4})?}
zip_regex_canada = %r{[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d}

validates :shipping_zip, :presence => true, :format => { :with => zip_regex_usa }, :if => :shipping_to_usa?
validates :shipping_zip, :presence => true, :format => { :with => zip_regex_canada }, :if => :shipping_to_canada?
validates :billing_zip, :presence => true, :format => { :with => zip_regex_usa }, :if => :billing_to_usa?
validates :billing_zip, :presence => true, :format => { :with => zip_regex_canada }, :if => :billing_to_canada?

def shipping_to_usa?
  shipping_country == 'US'
end

def billing_to_usa?
  billing_country == 'US'
end

def shipping_to_canada?
  shipping_country == 'CA'
end

def billing_to_canada?
  billing_country == 'CA'
end

如何使这段代码更优雅,为每个字段编写一条验证行?

2 个答案:

答案 0 :(得分:1)

您可以使用gem validates_as_postal_code

它允许您检查这样的邮政编码:

class Person < ActiveRecord::Base
   validates_as_postal_code :postal_code, :country => "CA", :allow_blank => true
end

还有更多选项

修改 还有一个不错的宝石:going_postal检查一下!

答案 1 :(得分:0)

我把一些东西放在这个宝石中:validates_zipcode

它目前支持 259个国家邮政编码格式,并且与Rails 3&amp; 4。

你可以像这样使用它:

class Address < ActiveRecord::Base
  validates_zipcode :zipcode
  validates :zipcode, zipcode: true
  validates :zipcode, zipcode: { country_code: :ru }
  validates :zipcode, zipcode: { country_code_attribute: :my_zipcode }
end