如何验证数组字段的成员? [英] How do I validate members of an array field?

查看:35
本文介绍了如何验证数组字段的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个模型:

class Campaign

  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, :type => String
  field :subdomain, :type => String
  field :intro, :type => String
  field :body, :type => String
  field :emails, :type => Array
end

现在,我想验证emails数组中的每个电子邮件的格式是否正确.我阅读了Mongoid和ActiveModel :: Validations文档,但没有找到具体方法.

Now I want to validate that each email in the emails array is formatted correctly. I read the Mongoid and ActiveModel::Validations documentation but I didn't find how to do this.

你能给我看看一个指针吗?

Can you show me a pointer?

推荐答案

您可以定义自定义ArrayValidator.将以下内容放入app/validators/array_validator.rb:

You can define custom ArrayValidator. Place following in app/validators/array_validator.rb:

class ArrayValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, values)
    Array(values).each do |value|
      options.each do |key, args|
        validator_options = { attributes: attribute }
        validator_options.merge!(args) if args.is_a?(Hash)

        next if value.nil? && validator_options[:allow_nil]
        next if value.blank? && validator_options[:allow_blank]

        validator_class_name = "#{key.to_s.camelize}Validator"
        validator_class = begin
          validator_class_name.constantize
        rescue NameError
          "ActiveModel::Validations::#{validator_class_name}".constantize
        end

        validator = validator_class.new(validator_options)
        validator.validate_each(record, attribute, value)
      end
    end
  end
end

您可以在模型中像这样使用它:

You can use it like this in your models:

class User
  include Mongoid::Document
  field :tags, Array

  validates :tags, array: { presence: true, inclusion: { in: %w{ ruby rails } }
end

它将针对array哈希中指定的每个验证器来验证数组中的每个元素.

It will validate each element from the array against every validator specified within array hash.

这篇关于如何验证数组字段的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆