Simple Ruby Input Validation Library

天大地大妈咪最大 提交于 2019-12-03 18:51:17

问题


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.


回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/3416484/simple-ruby-input-validation-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!