diff --git a/gems/reform/api.md b/gems/reform/api.md index 8e138f91..f2ff0732 100644 --- a/gems/reform/api.md +++ b/gems/reform/api.md @@ -210,6 +210,8 @@ The model won't be touched, its values are still the original ones. model.artist.name #=> "Duran Duran" +You can find more options and validation examples [here](/gems/reform/validation.html). + ### Deserialization and Populator Very often, you need to give Reform some information how to create or find nested objects when `validate`ing. This directive is called _populator_ and [documented here](http://trailblazer.to/gems/reform/populator.html). diff --git a/gems/reform/validation.md b/gems/reform/validation.md index 2f914e03..1a50008c 100644 --- a/gems/reform/validation.md +++ b/gems/reform/validation.md @@ -89,6 +89,33 @@ At any time you can extend an existing group using `:inherit`. This appends validations to the existing `:email` group. +## Conditional Validation + +Sometimes you need to run validations based on data of your form. This can be easily done with conditional validations. + + require "reform/form/dry" + + class Fund::CreateCallForm < Reform::Form + feature Reform::Form::Dry + + property :type + property :fund + + validation do + required(:type) { filled? & included_in?(TRANSACTION_TYPES['Fund::Call']) } + end + + validation if: -> (results) { rebalance? } do + required(:fund).filled + end + + def rebalance? + self.type == 'rebalance' + end + end + +Our form has two properties `type` and `fund` and fund is required only if type is `type == 'rebalance'`. + ## Dry-validation Dry-validation is the preferred backend for defining and executing validations.