conformist icon indicating copy to clipboard operation
conformist copied to clipboard

Allow validation of tuples

Open aronerben opened this issue 2 years ago • 4 comments

Some values should be validated together, for example, for SMTP validation, either both a username and a password are given or neither. The situation where one is given but not the other should not happen. I propose the following construct:

let smtp_schema =
  let open Conformist in
  make
    [ optional (string "SMTP_USERNAME")
    ; optional (string "SMTP_PASSWORD")
    ]
    smtp_config
;;

becomes

let smtp_schema =
  let open Conformist in
  make
    [ optional (pair (string "SMTP_USERNAME") (string "SMTP_PASSWORD"))    ]
    smtp_config
;;

Now Conformist should make sure that either both SMTP_USERNAME and SMTP_PASSWORD are given or neither.

aronerben avatar Aug 12 '22 14:08 aronerben

@aronerben Doesn't this example lend itself to using a custom type that itself is optional in the schema? This way you can enforce your constraint at compile time as well.

joseferben avatar Aug 13 '22 04:08 joseferben

Can you elaborate? Do you propse using optional (custom ...)? From what I'm seeing now Conformist.custom maps to one value in the input, so I can't use a single custom to cover both SMTP_USERNAME and SMTP_PASSWORD

aronerben avatar Aug 13 '22 11:08 aronerben

@aronerben For your case I suggest to use one value in the input, because you seem to want to enforce "either both are there or neither are there". But I like the idea to add tuple/pair types, maybe even up to a certain arity?

joseferben avatar Aug 14 '22 04:08 joseferben

We would have to combine the value in our env file with a custom delimiter for it to be one value in the input (as we are using Sihl.Configuration). I think an n-tuple type would be great here

aronerben avatar Aug 14 '22 16:08 aronerben