Validations module for Crystal
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
spec feat: improve composition, add `.rule` macro Sep 29, 2018
src feat: improve composition, add `.rule` macro Sep 29, 2018
.editorconfig initial commit Aug 26, 2018
.gitignore initial commit Aug 26, 2018
.travis.yml fix: travis build Sep 19, 2018
LICENSE initial commit Aug 26, 2018
README.md bump: 0.1.5 Sep 29, 2018
shard.yml bump: 0.1.5 Sep 29, 2018

README.md

Validations

Built with Crystal Build status Docs Releases Awesome vladfaust.com Patrons count

A validations module for Crystal.

Become a Patron

Installation

Add this to your application's shard.yml:

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

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

Usage

This shards allows validation composition (i.e. inclusion of modules with custom validations and rules).

require "validations"

module CustomValidations
  include Validations

  rule :email do |attr, value, rule|
    invalidate(attr, "must be an email") unless /@/.match(value)
  end
end

struct User
  include Validations
  include CustomValidations

  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), email: true
  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)
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 be an email"],
#   "@age" => ["must be greater than or equal to 18"]
# }

List of currently implemented rules

  • is: Object - check if attribute == object
  • gte: Comparable - check if attribute >= comparable
  • lte: Comparable - check if attribute <= comparable
  • gt: Comparable - check if attribute > comparable
  • lt: Comparable - check if attribute < comparable
  • in: Enumerable - check if enumerable.includes?(attribute)
  • size: Enumerable - check if enumerable.includes?(attribute.size)
  • size: Int - check if attribute.size == int
  • regex: Regex - check if regex.match(attribute)

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