I am trying to validate an email address.. whether it is present or not.. and whether it meets a regex criteria (/xyz/). I really need to do this on the controller or view level in rails as I am going to be dumping ActiveRecord for my app as I am planning on using a nosql database later.
Any hints? Suggestions?
In the model, it would be the following code.. but I'm trying to do this in controller or view:
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
class UsersController < ApplicationController
def create
user = User.new(params[:user])
if valid_email?(user.email)
user.save
redirect_to root_url, :notice => 'Good email'
else
flash[:error] = 'Bad email!'
render :new
end
end
private
def valid_email?(email)
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
email.present? &&
(email =~ VALID_EMAIL_REGEX) &&
User.find_by(email: email).empty?
end
end
However, I would say that validation still belongs in the model, even if it isn't an ActiveRecord-based one. Please take a look at how to use ActiveModel::Validations:
http://api.rubyonrails.org/classes/ActiveModel/Validations.html http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ http://asciicasts.com/episodes/219-active-model
You can leave it in the model even if you use nosql later on. Just use ActiveModel instead of ActiveRecord. For example, do not inherit from ActiveRecord.
class ModelName
include ActiveModel::Validations
attr_accessor :email
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
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