2017-02-15 71 views
4

我想为我的应用程序添加一个电子邮件自定义验证器;但是,我应该在哪里放置自定义验证器? (我真的不想把这个验证器类放在模型中)是否有验证器的cli生成器?我应该在Rails 5中放置自定义验证器?

http://guides.rubyonrails.org/active_record_validations.html

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 Person < ApplicationRecord 
    validates :email, presence: true, email: true 
end 

什么是用于自定义验证公约位置/路径?

回答

9

我把它们放在/app/validators/email_validator.rb中,验证器会自动加载。

此外,我不知道这是你的情况,但你应该用你的形式替换它。如果是这样,在用户到达控制器之前进行第一次验证。

<div class="field"> 
    <%= f.label :email %> 
    <%= f.text_field :email, required: true %> 
    </div> 

通过:

<div class="field"> 
    <%= f.label :email %> 
    <%= f.email_field :email, required: true %> 
    </div> 
+0

的是,在轨道公约?并将它自动加载? –

+0

显然[SO:5263239](http://stackoverflow.com/questions/5263239/where-should-rails-3-custom-validators-be-stored),[SO:35953656](http://stackoverflow.com#/questions/35953656/where-exactly-do-i-put-autoload-path-for-custom-validator-in-config-application) – devoh

+0

感谢您的额外信息。我只使用api导轨。 :D –

1

我的验证程序没有自动加载。至少没有显示时,我在控制台输入:

> ActiveSupport::Dependencies.autoload_paths 

所以,我把我的config/application.rb中,这条线:

config.autoload_paths += %W["#{config.root}/lib/validators/"] 
+1

'lib /'文件夹不是自动加载的。他们从rails 5中删除了lib自动加载。 您应该创建该文件夹并在其中放置验证程序。 'app/validators /' 然后它们将被自动加载,所以你不需要在config.autoload_paths中进行任何设置。 – zhisme