简单的Ruby输入验证库 [英] Simple Ruby Input Validation Library

查看:65
本文介绍了简单的Ruby输入验证库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在到处寻找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.

推荐答案

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

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

这篇关于简单的Ruby输入验证库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆