I put EmailValidator in lib/validators/email_validator and it's not workings (I put root/lib in the load_path)
here is the code.. I put the class in module validators as the parent folder name
class Validators::EmailValidator < 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 get the error Unknown validator: 'email'
You have two options:
config/initializers
.Or add lib/validators
to the autoload path in config/application.rb
.
config.autoload_paths << "#{config.root}/lib/validators"
Personally I would go with the second option as lib/validators
makes for good encapsulation.
Since you put your custom validator in the Validators::
in the lib/validators
, you have to reference it with that namespace also.
validates :email, presence: true, :'validators/email' => true
UPDATE: You need this:
module Validators
class EmailValidator < ActiveModel::EachValidator
def validate(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
end
class YourModel < ActiveRecord::Base
include Validators
validates :email, :presence => true, :email => true
end
Otherwise, you need to put your validator class under the ActiveModel::Validations
namespace. When you namespace a class, ActiveRecord isn't going to see it, if that namespace isn't a namespace it has already included.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With