# How to define conditional rules

**URL:** https://discourse.dry-rb.org/t/how-to-define-conditional-rules/1292
**Category:** dry-validation
**Created:** [June 30, 2021, 1:54pm UTC](https://discourse.dry-rb.org/t/how-to-define-conditional-rules/1292 "2021-06-30T13:54:52Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![morgoth](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/morgoth/32/667_2.png) [@morgoth](https://discourse.dry-rb.org/u/morgoth)
#### Post date: [June 30, 2021, 1:54pm UTC](https://discourse.dry-rb.org/t/how-to-define-conditional-rules/1292/1 "2021-06-30T13:54:52Z")

</div>

I would like to “run” a rule only when the attribute/key is truthy, so something like:

```auto
class Search < Dry::Validation::Contract
  params do
    optional(:email).value(:string)
  end

  rule(:email) do
    key? && SomeLogicForValidation(value)
  end
end

```

Here I would like to get rid of “key?” somehow.  
When I try with early return like `return unless key?` I’m getting an error: `LocalJumpError`.

Is it already possible somehow?

---

<div class="post-metadata">

### Author: ![alassek](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/alassek/32/314_2.png) [@alassek](https://discourse.dry-rb.org/u/alassek)
#### Post date: [June 30, 2021, 5:46pm UTC](https://discourse.dry-rb.org/t/how-to-define-conditional-rules/1292/2 "2021-06-30T17:46:51Z")

</div>

There’s [an open issue](https://github.com/dry-rb/dry-validation/issues/678) with a potential new API for this, but for now you will have to rely on guard clauses.

The LocalJumpError happened because Procs don’t trap `return`, and the code is not running inside a method. Inside a proc you may use `next` to achieve the same result:

```ruby
next unless key?

```

The difference between Proc and Lambda [can be confusing](https://medium.com/rubycademy/procs-and-lambdas-46433b93080d) but they each serve a different purpose, and work slightly differently because of that.

FWIW I usually write this kind of rule as

```ruby
rule :email do
  SomeLogicForValidation(value) if key?
end

```

which honestly doesn’t seem that bad

---

<div class="post-metadata">

### Author: ![morgoth](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/morgoth/32/667_2.png) [@morgoth](https://discourse.dry-rb.org/u/morgoth)
#### Post date: [July 1, 2021, 6:42am UTC](https://discourse.dry-rb.org/t/how-to-define-conditional-rules/1292/3 "2021-07-01T06:42:05Z")

</div>

Thank you. `next` works fine.  
I added a bit simplified example. In my case the validation is few lines of codes, so the early return makes it much nicer.

Proposition with adding a guard to DSL looks nice.
