Validate - simple & flexible input validation

you’re right that is a common issue, we could maybe add a built in cast: :integer rule that handles this automatically by trying to cast to the provided type, and returning a validation error if it fails.

in the mean time, you could accomplish this with a custom validation rule that passes the transformed value to the success result like:

rules = %{
  "id" => [
    required: true,
    custom: fn %{ value: value } ->
      case Integer.parse(value) do
        {id, _} -> Validate.Validator.success(id)
        _ -> Validate.Validator.halt("must be an integer")
      end
    end
}

input = %{"id" => "123"}

{:ok, data} = Validate.validate(input, rules)

data["id"] == 123
2 Likes