0

我有一个消息模型,我一直在查看各种 gems/js 以进行客户端验证。然后我开始阅读有关 Active Model Validations 的内容,我对 Rails 很陌生,所以请原谅我没有完全理解文档。

首先,我是否正确地说我可以使用 ActiveModel Validation 执行客户端验证并设置我自己的自定义错误消息

我在消息模型的顶部

include ActiveModel::Validations

进一步阅读已确定

我应该使用

 validates_with MyValidator

但这不起作用,因为我收到错误消息

uninitialized constant Message::MyValidator

如果我把它放在模型中

我也读过-

 To cause a validation error, you must add to the record‘s errors directly from within the validators message

class MyValidator < ActiveModel::Validator
def validate(record)
record.errors.add :base, "This is some custom error message"
record.errors.add :first_name, "This is some complex validation"
# etc...
end

所以这是说我可以在客户端添加我自己的自定义错误消息?

我目前的问题是弄清楚它要做什么,我把这些类和方法放在哪里等等。如果有人能指出我正确的方向,我将不胜感激,我真的很想学习

谢谢

4

1 回答 1

1

ActiveModel 验证不提供客户端验证。如果您想在客户端使用 Rails 验证器,我建议您使用client_side_validations gem。

如果您在开始时遇到问题,我建议您在模型中执行一个简单的验证,并在尝试将其移动到客户端之前验证它是否有效。例如,在您的Message班级中:

# app/models/message.rb
class Message
  include ActiveModel::Validations
  attr_accessor :sender
  validates :sender, presence: true
end

# in the console
m = Message.new

m.valid?                #=> false
m.errors.full_messages  #=> ["Sender can't be blank"]

然后开始使用其他类型validates的.validatevalidates_with

于 2012-11-24T14:23:11.820 回答