Validations

Built with Crystal Build status Docs Releases Awesome vladfaust.com

A validations module.

Installation

Add this to your application's shard.yml:

dependencies:
  validations:
    github: vladfaust/validations.cr
    version: ~> 0.1.4

This shard follows Semantic Versioning 2.0.0, so see releases and change the version accordingly.

Usage

require "validations"

struct User
  include Validations

  property name : String
  property email : String
  @age : UInt8?
  @nilable : String?

  def initialize(@name, @email, @age : UInt8? = nil, @nilable : String? = nil)
  end

  validate name, size: (1..16)
  validate email, size: (6..64), regex: /\w+@\w+\.\w{2,}/
  validate @age, gte: 18

  # Will not be run if `@nilable.nil?`
  validate @nilable, size: (5..10)

  # Custom validations are allowed
  def validate
    previous_def
    invalidate("name", "must not be equal to Vadim") if name == "Vadim"
  end
end

user = User.new("Vadim", "e-mail", 17)
pp user.valid?
# false
pp user.invalid_attributes
# {
#   "name" => ["must have size in (1..16)", "must not be equal to Vadim"],
#   "email" => ["must have size in (6..64)", "must match /\\w+@\\w+\\.\\w{2,}/"],
#   "@age" => ["must be greater than or equal to 18"]
# }

Currently implemented inline validations

Contributing

  1. Fork it (https://github.com/vladfaust/validations.cr/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors