Validate in elixir Without Ecto and ...

Hey
how you validate this %{“age” => age,“name” => name} without ecto changeset :

def make(conn,%{"name" => name,"age" => age} = params) do
end

1 - both of params should be exist
2 - age must be integer and between 12…50
3-name must be string
4- age != nil and name != nil
5- name length > 3
6- age !="" and name != “”

how you validate this without any library ? also i want to print a good message for any state :
%{“age” => age,name => “”} -> puts “name is empty”
%{“name” => name,“age” => nil} -> puts “age is nil”
%{“name” => nil,“age” => nil} -> puts “age and name is nul”

how you do this ? what is the best way to do this?

1 Like
  1. pattern match
  2. guard clause, when is_integer(age) and age >= 12 and age <= 50
  3. guard clause, when is_binary(…)
  4. guard clause, not is_nil …
  5. String.length
  6. when not(name=="") etc.

The best way to do this is… use ecto :slight_smile:

You will need to reinvent the wheel for validation, for error message.

And now, with latest ecto 3, changesets have been separated from sql.

Of course You could make it without… but You will see that writing functions with long guard clauses is painful. In that case, I would probably use cond do … end

PS. not is_nil(), age is not “” are probably redundant, as You could only test for is_binary() and is_integer().

6 Likes

@morteza: Here is example code:

defmodule Example do
  def sample(_conn, %{"age" => age, "name" => name} = _params), do: do_sample(age, name)
  def sample(_conn, %{"name" => _name} = _params), do: {:error, "age does not exists"}
  def sample(_conn, %{"age" => _age} = _params), do: {:error, "name does not exists"}
  def sample(_conn, _params), do: {:error, "age and name does not exists"}

  # UTF-8 version
  def do_sample(age, <<_::utf8, _::utf8, _::utf8, _::binary>>) when age in 12..50, do: :ok
  # NON-UTF8 version:
  # def do_sample(age, <<_::binary-size(3), _::binary>>) when age in 12..50, do: :ok
  def do_sample(age, _name) when is_nil(age), do: {:error, "age can't be nil"}
  def do_sample(age, _name) when not is_integer(age), do: {:error, "age is not integer"}
  def do_sample(age, _name) when age not in 12..50, do: {:error, "age must be between 12 and 50"}
  def do_sample(_age, name) when is_nil(name), do: {:error, "name can't be nil"}
  def do_sample(_age, name) when not is_binary(name), do: {:error, "name is not binary"}
  def do_sample(_age, _name), do: {:error, "name should have at least 3 characters"}
end
2 Likes

@kokolegorille @Eiji thank you

1 Like

@morteza you can use this lib https://github.com/sticksnleaves/justify

there is a thread about this lib here Is anybody interested in an Ecto like validation library?

1 Like

@morteza or you can this lib https://github.com/hrzndhrn/xema

2 Likes