正则表达式与自定义验证轨道匹配

时间:2014-10-07 13:33:43

标签: ruby-on-rails ruby regex ruby-on-rails-4

尝试创建自定义验证方法但收到错误

wrong number of arguments (0 for 1..3)

我想验证邮政编码的格式,但提供自定义错误信息,而不是我收到的信息,如果我这样做

validates_format_of :postcode, with: /\A^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[ ]{0,1}[0-9][ABD-HJLNP-UW-Z]{2})$\z/i, message: 'Please check your postcode'

这将显示

的错误消息
postcode Please check your postcode

所以我虽然能做到这一点

class User < ActiveRecord::Base
validate :format_postcode

 def format_postcode
  regexp = /\A^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[ ]{0,1}[0-9][ABD-HJLNP-UW-Z]{2})$\z/i
   if !postcode.match(regexp)
     errors.add[:base] << "Please check your Postcode"
   end
 end
end

但是这会引发错误

我在这里做错了什么?

由于

1 个答案:

答案 0 :(得分:1)

问题在于这一行

errors.add[:base] << "Please check your Postcode"

应该是

errors.add :base, "Please check your Postcode"

正如错误消息所示,add是一个获取1..3参数的方法,而不是数组的getter。