Within a model class, you can setup validations. Validations let you restrict the types of data that can be stored in a model. Validations are mostly useful for the store
collection, though they can be used elsewhere.
At the moment, we have the following validations (with more on the way):
See this folder for more info on the validators.
class Info < Volt::Model
validate :name, length: 5
validate :state, presence: true
end
When save!
on a buffer with validations is called, the following occurs:
save!
is rejected with the error object.You can create a one-off custom validation by passing a block to validate:
validate do
if _name.present?
{}
else
{ name: ['must be present'] }
end
end
The block should return a hash of errors. Each key relates to an array of error messages for the field. You can return multiple errors and they will be merged.
You may wish to use an existing validator only in certain situations. For example, you may have a blog post that has a publish_date that should be set, but only when the post is published. You can use any validator within a validations
block (notice the plural).
class Post < Volt::Model
field :title, String
field :published, Volt::Boolean
field :publish_date
validate :title, length: 5
validations do
if published
validate :publish_date, presence: true
end
end
end
Note: the Boolean type is currently not supported. Volt adds a Volt::Boolean class you can use
You can also specify that the validation should only happen on create or update:
class Post < Volt::Model
field :published, Boolean
field :publish_date
validations(:update) do
if _published
validate :publish_date, presence: true
end
end
end
Lastly, validations
passes in :create or :update based on the state.
class Post < Volt::Model
...
validations do |action|
if action == :update && _published
validate :publish_date, presence: true
end
end
end
TODO: Document custom validator classes