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:

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.

Where Next?

Popular in Libraries Top

grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
cjen07
parameterized pipe in elixir: |n&gt; edit: negative index in |n&gt; and mixed usage with |&gt; are supported example: use ParamP...
New
tfwright
After working on it for a couple of months and using it in production for most of that time, today I’ve released LiveAdmin, a LiveView ba...
New
woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
ahamez
Hi everyone, I’ve been working on this protobuf library for 3 years. We use it in the company I work for, EasyMile, to communicate with ...
New
tmbb
I’ve decided to create this topic to discuss optimization possibilities for something like Phoenix LiveView. I’ve created this topic unde...
New
mtrudel
Bandit is an HTTP server for Plug and WebSock apps. Bandit is written entirely in Elixir and is built atop Thousand Island. It can serve...
New
gjaldon
As the title states, EctoEnum has just been updated after some time of hardly any activity in the repo. Here’s the latest release: https:...
New
anshuman23
Hello all, I have been working on my proposed project called Tensorflex as part of Google Summer of Code 2018.. Tensorflex can be used f...
New
maltoe
Hello! Came here to announce ChromicPDF, a pet project PDF generator I’ve been working on for the past few months. Why another PDF gener...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Sub Categories:

We're in Beta

About us Mission Statement