validations.cr v0.2.1
Validations
A validations module for Crystal.
Supporters
Thanks to all my patrons, I can continue working on beautiful Open Source Software! 🙏
Lauri Jutila, Alexander Maslov, Dainel Vera, Anton Yordanov
You can become a patron too in exchange of prioritized support and other perks
Installation
Add this to your application's shard.yml
:
dependencies:
validations:
github: vladfaust/validations.cr
version: ~> 0.2.0
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), presence: true
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 ifattribute == object
presence: Bool
- check unlessattribute.nil?
gte: Comparable
- check ifattribute >= comparable
lte: Comparable
- check ifattribute <= comparable
gt: Comparable
- check ifattribute > comparable
lt: Comparable
- check ifattribute < comparable
in: Enumerable
- check ifenumerable.includes?(attribute)
size: Enumerable
- check ifenumerable.includes?(attribute.size)
size: Int
- check ifattribute.size == int
regex: Regex
- check ifregex.match(attribute)
Rules which need to be explicitly required
Some rules are not required with require "validations"
, you have to require them explicitly.
require "validations/rules/scheme"
(related to URI scheme)scheme: String
- check ifattribute.scheme == string
scheme: Enumerable
- check ifenumerable.includes?(attribute.scheme)
Contributing
- Fork it (https://github.com/vladfaust/validations.cr/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- @vladfaust Vlad Faust - creator, maintainer
Repository
validations.cr
Owner
Statistic
- 13
- 2
- 4
- 2
- 0
- over 4 years ago
- August 26, 2018
License
MIT License
Links
Synced at
Sun, 17 Nov 2024 02:32:53 GMT
Languages