Reputation: 6870
Is there a native way to define validations for a Crystal object ? Let's consider this class:
class Person
def initialize(@age : Int32)
end
end
How could I add a simple validation if age < 18
?
Ex:
Person.new(10)
>> Error: attibute 'age' should be greater than 18
I saw a 3rd party library doing this but I'd like to avoid adding dependencies.
Upvotes: 0
Views: 58
Reputation: 2999
There is no automated way to achieve runtime validation, but there is an idiomatic way:
def initialize(@age)
raise ArgumentError.new("age must be 18 or more") if @age < 18
end
Upvotes: 3