Question

I am following the official documentation in order to create a simple custom validation that checks if an email address is formatted properly.

In applications lib folder I have creating file with name email_format_validator.rb that contains the following code:

class EmailFormatValidator < ActiveModel::EachValidator

  def validate_each(object, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      object.errors[attribute] << (options[:message] || "is not formatted properly")
    end
  end

end

and in my model I have the following check:

validates :email, presence: true, email_format: true

If I comment the email_format: true part the views are accessible, otherwise, an error on this row is generated as it is displayed on the screenshot below:

enter image description here

Was it helpful?

Solution

lib is not automatically added to the LOAD_PATH. To fix the issue, either append the lib folder in config.autoload_paths or add a require at the beginning of the model

require 'lib/email_format_validator'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top