nehero

nehero

Validate - simple & flexible input validation

Hey! One thing I’ve been struggling with since switching to elixir and phoenix is validating incoming request data, whether it be from an API route or an html form. Coming from the Laravel world, I was used to having a powerful request validation system baked in that isn’t tied to your data schema.

So I created Validate

GitHub:
https://github.com/ozziexsh/validate

Docs:

TL;DR and examples

Features include:

  • Lots of validation rules built in
  • Custom validation rules via inline functions or modules
  • Plug compatibility (validate and authorise controller actions before reaching the method)
  • Automatically strips keys from maps that aren’t present in the rules, preventing attackers from throwing extraneous data at you
  • Infinite nesting of lists/maps to support complex JSON structures

There are lots of examples in the readme but here’s a quick look at how you could use it:

input = %{
  "email" => "test@example.com",
  "plan" => "free",
  "team" => %{"name" => "Test Team"}
}

rules = %{
  "email" => [required: true, type: :string, max: 50],
  "plan" => [required: true, type: :string, in: ["free", "pro"]],
  "team" => [
    required: true,
    type: :map,
    map: %{"name" => [required: true, type: :string]}
  }
}

# depending on the result
{:ok, data} = Validate.validate(input, rules)
{:error, errors} = Validate.validate(input, rules)

Why not just ecto?

Although you can technically do form validation through ecto changesets directly on your schemas, and embedded changesets for other data, I found I was constantly typing the same stuff over again, and it quickly gets complicated once you start working with nested and optional data.

Why not library x/y/z?

There are a few great validation libraries out there already but I wanted more than seemed to be offered. Stripping extraneous keys, nesting of maps/lists, and built-in plug support were all hard to find in one single library.

Is it fast?

Honestly, not sure. I have not benchmarked it on massive lists or multi-MB payloads yet. Since we are potentially stripping keys out of the input it means we have to keep a second copy of the data as we loop through and validate. I’m sure this could be optimised more than I have it currently, but I am still learning :slight_smile:

Will more validation rules be added?

Yes! Right now I’ve been using Laravel’s validation rules as inspiration for rules but there are still a few missing which I will add over time. In the meantime, if you find that a rule is not present you can write an inline custom validator really easily.


Would love any feedback/critique! I’ve been using elixir off and on over the years but only recently started writing it daily these past few months, so some of the code has room to be improved.

This package was a lot of fun to build :smile:

Most Liked

nehero

nehero

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
nehero

nehero

just released v1.3.0 which added a bunch of new validation rules:

  • cast
  • characters
  • ip
  • url
  • uuid
  • date_string
  • ==
  • >
  • >=
  • <
  • <=
Hermanverschooten

Hermanverschooten

I like the library, but one thing that’s been bothering me recently is that when you specifiy an :id in a path, the resulting value in your params will be a string even though you want it to be an integer.
I’d love for the type: :integer check to allow for this and return the integer value.

Last Post!

krishna_vaguelyright

krishna_vaguelyright

Hi! Do we have conditional validation dependent on other fields here?

Where Next?

Popular in Announcing Top

bryanjos
Hi, I just published version 0.23.0 of Elixirscript. https://github.com/bryanjos/elixirscript/blob/master/CHANGELOG.md Most of the chan...
New
tmbb
I’ve decided to create this topic to discuss optimization possibilities for something like Phoenix LiveView. I’ve created this topic unde...
144 10809 141
New
kip
ex_cldr provides localisation and internationalisation support based upon the data from the Unicode CLDR project. Unicode released CLDR ...
407 13300 120
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
oltarasenko
Dear Elixir community, After a year of development, bug fixes, and improvements, we are proudly ready to share the release of Crawly 0.1...
New
nikokozak
Hello all, I’ve been working on Svonix - a library for quickly integrating Svelte components into Phoenix views. It’s a much-needed succ...
New
brainlid
LangChain is short for Language Chain. An LLM, or Large Language Model, is the “Language” part. This library makes it easier for Elixir a...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 130579 1222
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31525 112
New

We're in Beta

About us Mission Statement