Reputation: 3945
I am using rails 4, and I am I creating an engine. In this engines .gemspec
I did the following:
s.add_dependency "rails", "~> 4.0.3"
s.add_dependency 'pg'
s.add_dependency 'bcrypt-ruby'
s.add_dependency 'validates_email_format_of' #Hi I am right here
s.add_development_dependency 'rspec-rails'
s.add_development_dependency 'letter_opener'
s.add_development_dependency 'pry'
s.add_development_dependency 'pry-rails'
s.add_development_dependency 'database_cleaner'
s.add_development_dependency 'capybara'
s.add_development_dependency 'factory_girl_rails'
I followed these instructions on installing validates_email_format_of
and the bundle install
worked. How ever when I run bundle exec rspec
I get the error: Unknown validator: 'EmailFormatValidator'
My Model Looks Like this:
require 'bcrypt'
module Xaaron
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
validates :first_name, presence: true
validates :user_name, uniqueness: true, presence: true, length: {minimum: 5}
validates :email, presence: true, confirmation: true, uniqueness: true, email_format: {message: "Email Invalid"}, if: :new_record?
validates :password, presence: true, confirmation: true, length: { minimum: 10 }, if: :new_record?
def self.authenticate_user(user_name, password)
user = Xaaron::User.find_by(user_name: user_name)
if(user && user.password_hash == BCrypt::Engine.hash_secret(password, user.salt))
user
else
nil
end
end
def encrypt_password
if password.present?
self.salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, salt)
end
end
end
end
See nice and simple, the line validates :email, presence: true, confirmation: true, uniqueness: true, email_format: {message: "Email Invalid"}, if: :new_record?
is whats throwing the error. Now the docs state to use :email_format => {message: 'asdasdsad'}
But no matter how the syntax is, I get that error.
Thoughts?
Upvotes: 2
Views: 1442
Reputation: 961
Try restarting your rails server to re-load the validators:
rails server
Reference: rails 3 customize validator error
Upvotes: 0
Reputation: 556
All you have to do is add
require 'validates_email_format_of'
to the top of your file and you should be able to use the gem like normal.
Upvotes: 2
Reputation: 2353
You can use the example included on Ruby on Rails API.
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, (options[:message] || "is not an email") unless
value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
end
end
validates :email, presence: true, email: true
Or simply do this:
validates :email, presence: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }
Upvotes: 1