【问题标题】:Multiple format validations in RailsRails 中的多种格式验证
【发布时间】:2012-03-27 17:08:11
【问题描述】:

我有一个字段字符串foo,它必须满足四个条件:

  • 不能为空
  • 所有记录都必须是唯一的
  • 只能包含字母、数字和连字符
  • 不能以字符串“bar”开头

前两个由:presence:uniqueness 验证处理。后两者很容易通过正则表达式的:format 验证处理。

是否可以包含多个 :format 验证规则,具有不同的 :message 值?

我想避免将这两个条件组合成一个正则表达式。除了多条消息之外,我认为如果它们是不同的,则更容易阅读和书写。

理想情况下,我希望所有这些都包含在一个 validates 调用中,但这不是严格要求的。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 validation


    【解决方案1】:

    根据source code for the validates method,没有办法;你会得到一个 :format 键和一组选项作为哈希值。

    但是,没有什么能阻止我两次致电validates

    validates :foo, 
      :presence => true, 
      :uniqueness => true,
      :format => {
        :with => /^[\w\-]*$/,
        :message => 'may only contain letters, digits, and hyphen'
      }
    validates :foo, :format => { 
      :with => /^(?!bar)/, 
      :message => 'may not start with "bar"'
    }
    

    这似乎工作正常。

    【讨论】:

      【解决方案2】:

      一个验证可以嵌入多个属性,如Validator#validate source code。所以可以更干净如下:

      validates :foo, 
        :presence => true, 
        :uniqueness => true,
        :format => {`enter code here`
          :with => /^[\w\-]*$/,
          :message => 'may only contain letters, digits, and hyphen'
        },
        :format => { 
          :with => /^(?!bar)/, 
          :message => 'may not start with "bar"'
        }
      }
      

      【讨论】:

      • 第二个格式参数会覆盖前一个。
      • 这个答案应该被删除
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 2010-11-22
      • 1970-01-01
      相关资源
      最近更新 更多