achedeuzot

achedeuzot

Ecto_commons – Ecto common helper functions such as Changeset validators

This library contains common helpers used with Ecto.Changeset.

I noticed myself copying over validators from various projects multiple times. So I figured I’d create a common library. I know everyone likes to have their own validation logic but I tried keeping it as generic as possible so it’ll be useful for many situations.

For now, it contains validators for the following cases:

  • Date, DateTime and Time
  • EmailValidator: validate emails and exclude temporary email providers
  • URLValidator: validate URLs with various levels of strictness
  • StringValidator: validate a string has a given prefix
  • PostalCodeValidator: validate postal codes for multiple countries (to be improved)
  • SocialSecurityValidator: validate social security number (SSN)
  • LuhnValidator: validate Luhn-type numbers such as credit card numbers and other administrative codes.

Happy to receive feedback, pull requests from motivated folks and ideas for improvement :grinning: I hope this lib will grow into a set of good common ecto helpers and tools we can all benefit from.

Cheers !

Most Liked

achedeuzot

achedeuzot

Hi folks !

I’ve published v0.2.0 with your feedbacks.

  • I’ve improved the URLValidator by better documenting what is and what isn’t supported.
  • I’ve added all countries for the PostalCodeValidator (still no full database but a first sanity check of the format). The formats come from http://i18napis.appspot.com/, recommended by the (now deprecated) unicode postal code database.
  • I’ve added better documentation to EmailValidator and an opt-in approach to which checks you want to apply. I also added pow's package email validator and fixed some of the shortcomings found by @hauleth.
  • I’ve added the validate_many helper as it’s indeed common to validate multiple fields with the same options.

As usual, happy to have your feedbacks, issues and pull requests :slightly_smiling_face:

Cheers :wave:

Kurisu

Kurisu

Another helper I used not exactly for changeset but when using Ecto.Multi:

  @doc """
  Normalize Ecto.Multi transaction result so it returns
  {:ok, value} or {:error, failed_value}
  """
  def normalize(result, key \\ nil)
  def normalize({:error, _, failed_value, _}, _key), do: {:error, failed_value}
  def normalize({:ok, result}, key), do: {:ok, Map.get(result, key, result)}
  def normalize(result, _key), do: result

Example of usage:

  def create_slider(attrs \\ %{}) do
    changeset = Slider.changeset(%Slider{}, attrs)

    Multi.new()
    |> Multi.insert(:slider, changeset)
    |> Multi.update(:slider_with_image, &Slider.image_changeset(&1.slider, attrs))
    |> Repo.transaction()
    |> MyLib.Multi.normalize(:slider_with_image)
  end

This way in the Phoenix controller we don’t have to change the classic way to handle CRUD actions.

hauleth

hauleth

Seems that this is still not fully valid, as this do not allow [::1] as a domain part. Additionally it will allow .foo. as a domain, which is incorrect.

danschultzer

danschultzer

Pow Core Team

Good catch, thanks! Didn’t validate the domain properly.

I didn’t add IP addresses as it’s strongly discouraged with RFC 3696:

The domain name can also be replaced by an IP address in
square brackets, but that form is strongly discouraged except for
testing and troubleshooting purposes.

@achedeuzot you may want to take a look at the changes in Improve email validation · Issue #560 · pow-auth/pow · GitHub as I didn’t validate the domain properly. Each DNS label should be validated. There are also some additional validation that I didn’t include such as checking for reserved domains (like example.com, these domains can’t receive e-mail).

hauleth

hauleth

If you are making it into library, then make it correct validator. Or at least mention that it will match only on subset of possible addresses.

Why use custom regex for validating URL instead, well, URI module? Also, why is regex strictly allowing only HTTP(s) and FTP protocols? What about other like for example Gopher or IRC?

Well, without DB to lookup these postal codes, this validator makes little sense. In most cases you can get list of all possible postal codes for given country, so it should be quite simple to make them into in-memory database.

Where Next?

Popular in Libraries Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
cjen07
parameterized pipe in elixir: |n> edit: negative index in |n> and mixed usage with |> are supported example: use ParamP...
New
jakub-zawislak
Hi everyone, I’m coming from the Symfony (PHP) framework. I like Phoenix, but it has a one thing that was build much better in the Symfo...
New
mcrumm
If you would like to migrate away from node/npm/webpack while still using sass, the dart_sass package provides a installer and runner for...
New
blatyo
https://www.conduitframework.com/ The best overview for how things are tied together is this presentation. Modules and functions are pre...
New
Qqwy
Solution is a library to help you with working with ok/error-tuples in case and with-expressions by exposing special matching macros, as ...
New
woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
engineeringdept
I’ve just released the first version of Snap, an Elasticsearch client. It borrows ideas about application structure and process managemen...
New
bryanjos
Hi, I wanted share a small library we at Revelry Labs made for rendering react components from the server side. There are instructions fo...
New
mattludwigs
Grizzly is a library for working with Z-Wave devices. Z-Wave is a low-frequency radio protocol for controlling smart home devices on a me...
New

Other popular topics Top

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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

Sub Categories:

We're in Beta

About us Mission Statement