martinthenth / goal

A parameter validation library - based on Ecto
https://hexdocs.pm/goal
MIT License
71 stars 10 forks source link

Support custom regex for validation via config #84

Closed lucca65 closed 7 months ago

lucca65 commented 8 months ago

Hello there!

I'm a user of this library, its been amazing so far. I love how declarative it is with macros!

However, in my use case, I needed to run custom regex's, which are different from the default ones provided.

I've changed it so those custom regex could live together with the customized email, uuid, in the Configuration. Maybe we could have another mechanism to send custom regex directly, but this use case is perfect for me since my regex's never change nor come from the client.

Configure new regex

In the configuration file

config :goal,
  # From Goal's docs
  uuid_regex: ~r/^[[:alpha:]]+$/,
  email_regex: ~r/^[[:alpha:]]+$/,

  # Custom regex used by my library
  ledger_index_regex: ~r/^(\d+|current|closed|validated)$/,
  ledger_entry_regex: ~r/^[a-fA-F0-9]{64}$/,
  currency_regex: ~r/^(?!(XRP$))[A-Za-z0-9\?\!\@\#\$\%\^\&\*\(\)\{\}\[\]\|]{3}$|^(?![0]{2})[A-Fa-f0-9]{40}$/,
  public_key_regex: ~r/^n[1-9a-np-zA-NP-Z]{1,53}$/,
  account_address_regex: ~r/^r[1-9a-np-zA-NP-Z]{24,34}$/

Use it inside defparams:

  defparams "account_nfts" do
    required(:account, :string, format: :account_address)
    optional(:ledger_hash, :string, format: :ledger_entry)
    optional(:ledger_index, :string, format: :ledger_index)
end

I think this is pretty and idiomatic, while keeping the same structure the library already have.

Let me know your thoughts!

martinthenth commented 8 months ago

Hey! Thanks for your PR. I'm okay with this solution as a workaround to https://github.com/martinthenth/goal/issues/64. When that issue is resolved, then this workaround is liable to be removed in a major version update.

lucca65 commented 8 months ago

Ok! Sounds good!

I've fixed the failed CI error, should be good to go now!

martinthenth commented 7 months ago

Published the new version on Hex: https://hex.pm/packages/goal/0.3.2

martinthenth commented 6 months ago

Hi @lucca65! I'm preparing a version that includes support for passing module attributes to the schema. I know I said that this feature that was introduced may be removed when that support is added, but I see no harm in keeping it and I think it is a useful addition. So the feature will stay in version 1.0.0 🙇🏻

lucca65 commented 6 months ago

This is nice! Thanks for the headsup! I'll update my deps as soon as I get the release notifications and will let you know if I stumble upon any issues!

Happy to know the library is moving forward to 1.0.0!! 🎉