自定义验证,两行?

时间:2011-03-22 11:12:36

标签: ruby-on-rails ruby validation

有没有办法只使用几行代码来验证输入字段?

在使用自定义验证时,我没有这样做。

模型

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

验证

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

这就是我真正想做的事。

class Search < ActiveRecord::Base
  validates :email, :email => lambda  do |record, value|
    record.errors[:email] << "invalid field" unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
  end
end

这可能吗?

2 个答案:

答案 0 :(得分:0)

查看ActiveModel的validates_format_of http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_format_of

class Person < ActiveRecord::Base
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
end

或使用快捷方式:

class Person < ActiveRecord::Base
  validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create }
end

答案 1 :(得分:0)

这是我的解决方案。

class Search < ActiveRecord::Base
  validate :my_custom_validator

  def my_custom_validator
    if @email.to_s.match(/hello/)
      self.errors[:email] << "Email can't contain the word 'hello'"
    end
  end
end