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?
guard clause, when is_integer(age) and age >= 12 and age <= 50
guard clause, when is_binary(…)
guard clause, not is_nil …
String.length
when not(name=="") etc.
The best way to do this is… use ecto
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().
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