json_record icon indicating copy to clipboard operation
json_record copied to clipboard

Custom validations on embedded documents

Open activestylus opened this issue 14 years ago • 0 comments

Given the following validator which resides in config/initializers

class EmailFormatValidator < ActiveModel::EachValidator  
  def validate_each(object, attribute, value)  
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i  
      object.errors[attribute] << (options[:message] || I18n.t('bad_format'))  
    end  
  end  
end

And the embedded class

class Network
  include JsonRecord::EmbeddedDocument

  schema.key :address
  schema.key :type

  def email?; type == 'Email'; end

  with_options :if => :email? do |network|
    network.validate :address, :email_format => true
  end

When I save a Network instance with type == 'Email', it's completely ignoring my validation

I also tried:

validate :address, :email_format => true, :if => :email?

But no luck. Is there a different way I should be declaring custom validations, or does JsonRecord not support them?

activestylus avatar Jul 09 '11 13:07 activestylus