2013-12-23 91 views
0

EmailValidator類的內部模塊,如:自定義驗證軌道

module ActiveModel 
    module Validations 
    class EmailValidator < EachValidator 
     def validate_each(record, attribute, value) 
     if value.presence && (value =~ /\A[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]+\z/).nil? 
      record.errors[attribute] << (options[:message] || "is invalid") 
     end 
     rescue => e 
     record.errors[attribute] << (options[:message] || "is invalid") 
     end 
    end 
    end 
end 

我試圖用這個我的模型內,但面臨的負載錯誤,當我嘗試啓動軌道服務器=>email_validator.rb定義EmailValidatorLoadError

任何人都可以幫助我嗎?

+0

本模塊中一個叫做'email_validator.rb'文件? – Santhosh

+0

是的。這個文件是在lib/active_model/validations/email_validator.rb – Smita

+0

這個'config.autoload_paths + =%W(#{config.root}/lib) 'on application.rb? –

回答

0

我推薦使用the valid_email gem代替,因爲驗證電子郵件地址是一個真正的痛苦!

class User < ActiveRecord::Base 
    validates :email, :presence => true, :email => true 

    # ... 
end 

根據RFC另請參閱this humongous regular expression這實際上驗證的電子郵件地址822

+0

我正在使用活動資源。 有沒有什麼辦法可以在不使用gem的情況下使用電子郵件驗證並保持代碼乾燥。 – Smita

0

validates_format_of:電子郵件,:與=>〜/\A[A-Za-z0-9._%+-] + @ [A-Za-z0-9 .-] +。[A-Za-z] + \ z/

0

您可以嘗試這種語法並根據此 blog實現您的代碼,該代碼應該非常有用: -

class EmailValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
    if value.presence && (value =~ /\A[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]+\z/).nil? 
     record.errors[attribute] << (options[:message] || "is invalid") 
    end 
    rescue => e 
    record.errors[attribute] << (options[:message] || "is invalid") 
    end 
end 

只需將此文件放在應用程序中/validators/email_validator.rb

for rails 3自定義驗證請read這個博客。

在Rails 4

class EmailValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i 
    record.errors[attribute] << (options[:message] || "is not an email") 
    end 
end 
end 

class foo < ActiveRecord::Base 
    validates :email, presence: true, email: true 
end 

最後很簡單,乾燥後使用REG。 exp.:-

/\A[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]+\z/ 

這是改編自http://www.regular-expressions.info/email.html