Simple Ruby Input Validation Library
Asked Answered
C

3

11

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.

Clypeus answered 5/8, 2010 at 15:44 Comment(0)
P
9

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
Pleonasm answered 5/8, 2010 at 18:51 Comment(3)
Thanks for the suggestion and example. However, I'm looking for something that does not tie validations to models.Clypeus
The example I gave will work with any Ruby class that has attributes - can you give an example (code or pseudocode) of the way you'd like validation to work?Pleonasm
I ended up going this route. Thanks.Clypeus
N
0

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.

Nigelniger answered 31/12, 2013 at 20:17 Comment(0)
P
0

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

Pinsk answered 6/1, 2019 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.