2017-02-15 34 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