2013-12-23 92 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