简单的 Ruby 输入验证库

发布于 2024-09-13 01:22:58 字数 159 浏览 3 评论 0原文

我一直在到处寻找一个简单的 Ruby 输入验证库。一切似乎都指向 ActiveRecord(或类似的)。我没有使用 Rails,而是使用没有 ORM 的 Sinatra。验证用户输入的最佳方法是什么(不直接绑定到模型层)?简单的事情,比如“字符串长度”、“是数字”等。最好有一个很好的机制来声明错误消息。

I've been looking all over the place for a simple input validation library for Ruby. Everything seems to point towards ActiveRecord (or similar). I'm not using Rails, I'm using Sinatra without an ORM. What's the best approach for validating user input (without tying directly to the model layer)? Simple things like "string length", "is numeric" etc. Preferably with a nice mechanism for declaring error messages.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

白龙吟 2024-09-20 01:22:58

您可以使用 Rails 3 RC 中的 ActiveModel::Validations:

require 'active_model'
# this appears to be a bug in ActiveModel - it uses this, but does not require it
require 'active_support/core_ext/hash'

class Model
  include ActiveModel::Validations

  attr_accessor :name
  validates_presence_of :name
end

m = model.new
puts m.valid? # false
m.name = "John Doe"
puts m.valid? # true

You could use ActiveModel::Validations, from Rails 3 RC:

require 'active_model'
# this appears to be a bug in ActiveModel - it uses this, but does not require it
require 'active_support/core_ext/hash'

class Model
  include ActiveModel::Validations

  attr_accessor :name
  validates_presence_of :name
end

m = model.new
puts m.valid? # false
m.name = "John Doe"
puts m.valid? # true
So要识趣 2024-09-20 01:22:58

好吧,我自己写了一个 http://rubygems.org/gems/validates_simple ,我希望它会有所帮助。它验证哈希值,这是 Web 应用程序中最常见的输入结构。

Well i wrote one my self http://rubygems.org/gems/validates_simple , i hope it will help. It validates hashes which is the most common structure of the input in the web applications.

也只是曾经 2024-09-20 01:22:58

我还写了一份,因为我对现有的解决方案感到沮丧。您可以尝试 https://github.com/Goltergaul/definition 它可以执行类似的所有验证进行干验证但不那么混乱

I also wrote one because I was frustrated with the existing solutions. You can try https://github.com/Goltergaul/definition It can do all sort of validations similar to dry-validation but less confusing

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文