Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate presence and regex format in rails controller?

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 }
like image 652
sambehera Avatar asked Apr 03 '13 22:04

sambehera


2 Answers

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

like image 77
Unixmonkey Avatar answered Nov 05 '22 04:11

Unixmonkey


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 }
like image 26
fontno Avatar answered Nov 05 '22 04:11

fontno