Is there a way to validate an input field using just a few lines of code?
Right not I’ve to do this when using a custom validation.
Model
class Search < ActiveRecord::Base
validates :email, :presence => true, :email => true
end
Validator
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || "is not an email") unless
value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
end
end
end
This is what I really want to do.
class Search < ActiveRecord::Base
validates :email, :email => lambda do |record, value|
record.errors[:email] << "invalid field" unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
end
end
Is that possible?
Here is my solution.