# Define a Hash param that also accepts a String that is validates \*then\* parsed

**URL:** https://discourse.dry-rb.org/t/define-a-hash-param-that-also-accepts-a-string-that-is-validates-then-parsed/1799
**Category:** dry-validation
**Created:** [May 8, 2024, 10:40pm UTC](https://discourse.dry-rb.org/t/define-a-hash-param-that-also-accepts-a-string-that-is-validates-then-parsed/1799 "2024-05-08T22:40:27Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![postmodern](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/postmodern/32/696_2.png) [@postmodern](https://discourse.dry-rb.org/u/postmodern)
#### Post date: [May 8, 2024, 10:40pm UTC](https://discourse.dry-rb.org/t/define-a-hash-param-that-also-accepts-a-string-that-is-validates-then-parsed/1799/1 "2024-05-08T22:40:27Z")

</div>

I’m wondering how one would define a Hash param (ex: for HTTP headers) that accepts a String, which is first validated using a Regex, then parsed into a Hash. I know about `dry-types` `.constructor` and `dry-validations`’s `before(:key_coercer)`, but am unclear how to insert a validation rule specifically for String values, before the coercion from String to Hash.

---

<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: [May 10, 2024, 5:18pm UTC](https://discourse.dry-rb.org/t/define-a-hash-param-that-also-accepts-a-string-that-is-validates-then-parsed/1799/2 "2024-05-10T17:18:55Z")

</div>

I did something vaguely similar to this for XML, maybe this will help

```ruby
module Types
  XML = String.constrained(format: %r{^<\?xml}).constructor do |input, type|
    if input.is_a?(Nokogiri::XML::Document)
      input
    elsif type.valid?(input)
      Nokogiri.parse(input)
    else
      type.(input)
    end
  end
end

```
