【问题标题】:ActiveRecord validation statement containing ||包含 || 的 ActiveRecord 验证语句
【发布时间】:2014-01-27 08:00:35
【问题描述】:

我在网上做了一些搜索,了解如何使用“if”语句和单独定义的方法构建 ActiveRecord 验证。但是,我想知道是否可以简单地将两个验证组合在一起,如果其中一个为真,那么整个事情就通过了。

我想要做的是让用户输入一个联系人字段,该字段可以是电子邮件或电话号码,但不能同时是两者。显然我下面的代码不起作用,但我想知道类似的东西是否可以工作?

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
VALID_PHONE = /\d{10}/

validates :contact, presence: true, format: { with: VALID_EMAIL_REGEX } || presence: true, length: { is: 10 }, format: { with: VALID_PHONE }

【问题讨论】:

    标签: ruby-on-rails validation activerecord conditional


    【解决方案1】:

    我本来建议对 validates 回调使用标准的 :if 选项,但经过更多研究后,我发现您可能会从中受益:


    Custom Validations

    根据 Rails 指南:

    #app/models/concerns/my_validator.rb
    class MyValidator < ActiveModel::Validator
      def validate(record)
        unless record.name.starts_with? 'X'
          record.errors[:name] << 'Need a name starting with X please!'
        end
      end
    end
    
    #app/models/person.rb
    class Person
      include ActiveModel::Validations
      validates_with MyValidator
    end
    

    这允许您创建自己的验证方法,允许您将错误消息直接附加到实例变量中(然后显示在表单上)。对于你的问题,我会这样做:

    #app/models/concerns/phone_email_validator.rb
    class PhoneEmailValidator < ActiveModel::Validator
      def validate(record)
        contact = record.contact
        phone = /\d{10}/
        email = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    
        if contact.validate(phone) || contact.validate(email)
    
            if contact.validate(phone) && contact.length < 10
               error = "Length too short for phone number!"
            end
    
        else
          error = 'Needs To Be Phone Or Email '
        end
        record.errors[:contact] << error
      end
    end
    
    #app/models/person.rb
    class Person
      include ActiveModel::Validations
      validates_with MyValidator
    end
    

    函数过于冗长,可能无法与验证正则表达式一起使用;但无论哪种方式都是一个想法!

    【讨论】:

    • 谢谢,这是个好主意!我看到了可以制作的自定义方法,但没有想到以这种方式使用它。
    猜你喜欢
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2014-06-14
    • 2011-02-13
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多