【问题标题】:Rails conditional validation of Zip Code for many countriesRails 对许多国家/地区的邮政编码进行条件验证
【发布时间】:2012-04-05 07:58:47
【问题描述】:

我需要对美国和加拿大的邮政编码进行模型级验证。这段代码让我感觉很糟糕:

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

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

【问题讨论】:

标签: ruby-on-rails validation model conditional


【解决方案1】:

我将一些部分拼凑到这个宝石中:validates_zipcode

它目前支持 259 个国家 邮政编码格式,并且与 Rails 3 和 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

【讨论】:

    【解决方案2】:

    你可以使用 gem validates_as_postal_code

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

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

    还有更多选择

    编辑: 还有一个不错的宝石:going_postal 看看!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 2013-10-09
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多