Simple Validate
PORO validation mixin with no deps - borrowing ideas from validatable
Features
- Similar API to Rails
- No other dependencies
Usage
require 'simple_validate'
class Person
include SimpleValidate
attr_accessor :name, :age
validates_presence_of :name, :age
validates_type_of :age, as: :integer
end=> p = Person.new
=> #<Person:0x007f9431536408>
=> p.valid?
=> false
=> p.errors
=> #<SimpleValidate::Errors:0x007f94318b4df0
@messages=
{:age=>["can't be empty", "must be an integer"],
:name=>["can't be empty"]}>Presence
validates_presence_of :attributeType
validates_type_of :attribute, as: :stringFormat
validates_format_of :attribute, with: /[A-Z]+/Length
-
Possible length options include:
maximum,minimum,in,is. -
maximum,minimumandistake a single integer andintakes a range.
validates_length_of :attribute, in: 6..9Inclusion and Exclusion
-
incan take aRangeor anArray
validates_inclusion_of :domain, in: [:net, :com]
validates_inclusion_of :number, in: 5..10
validates_exclusion_of :name, in: [:Bojack, :Horseman]Options
Allow nil
validates_type_of :attribute, as: :string, allow_nil: trueCustom error messages
- It is possible to pass a custom error message to any validation.
validates_presence_of :attribute, message: 'attribute is required!'Conditional validation
- It is possible to pass an
ifoption with a proc for a conditional validation
validates_presence_of :attribute, if: Proc.new { true }Installation
gem 'simple_validate'License
The gem is available as open source under the terms of the MIT License.