【问题标题】:Client side validations undefined method `validates_email'客户端验证未定义方法“验证电子邮件”
【发布时间】:2013-01-25 15:49:18
【问题描述】:

我从 client_side_validations 页面复制了代码。我有错误 undefined method validates_email for #<Class:0x007ff3382428a8> 当我将includes ::Validations 放入我的模型中时,此错误消失了,但验证根本不起作用。

app/validators/email_validator.rb

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attr_name, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
    record.errors.add(attr_name, :email, options.merge(:value => value))
    end
  end
end

# This allows us to assign the validator in the model
module ActiveModel::Validations::HelperMethods
  def validates_email(*attr_names)
    validates_with EmailValidator, _merge_attributes(attr_names)
  end
end

config/locales/en.yml

# config/locales/en.yml
en:
  errors:
    messages:
      email: "Not an email address"

app/assets/javascripts/rails.validations.customValidators.js

// The validator variable is a JSON Object
// The selector variable is a jQuery Object
window.ClientSideValidations.validators.local['email'] = function(element, options) {
// Your validator code goes in here
if (!/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test(element.val())) {
// When the value fails to pass validation you need to return the error message.
// It can be derived from validator.message
return options.message;
}
}

models/comment.rb

class Comment < ActiveRecord::Base
  attr_accessible :content, :email, :ip, :name, :post_id
  belongs_to :post
  validates_presence_of :content, :email, :post_id, :name
  validates_email :email
end

【问题讨论】:

    标签: ruby-on-rails client-side-validation


    【解决方案1】:

    我没有看到你包括你的模块。此外,根据您放置模块的位置,您有时需要“要求”它。另外,试试:

    include <Module name>
    

    而不是

    includes <Module name>
    

    希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多