The new validator class introduced in the lib directory is not recognized and throws an error

Unknown validator: 'email_format'

Rails.root: /home/saran/work_space/rails_apps/test_app
Application Trace | Framework Trace | Full Trace

app/models/user.rb:2
app/controllers/user_controller.rb:5:in `create'

my user model file as below: -

class User < ActiveRecord::Base
  validates :email, :presence => true, :uniqueness => true, :email_format => true
end

my lib class is presented below:

:~/work_space/rails_apps/test_app/lib$ cat email_format_validator.rb 
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] || "is not formatted properly")  
    end  
  end  
end

I am using Rails version 3.0

+3
source share
2 answers

I had the same problem.

To solve this problem, I created a new "validators" folder in "config / lib".

Then I added this to config / application.rb:

config.autoload_paths += %W(#{config.root}/lib/validators/)
0
source

Change the user model as shown below:

class User < ActiveRecord::Base
   require "email_format_validator"
   validates :email, :presence => true, :uniqueness => true, :email_format => true
end
0
source

Source: https://habr.com/ru/post/1768834/


All Articles