简体   繁体   中英

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 }
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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM