Elixir Validation inspired from Laravel : Developed By Majid Ahmaditabar
Validation data in Elixir and Phoenix

Validation in Elixir and Phoenix

Majid Ahmaditabar

--

How To Validate data in elixir and phoenix framework? Elx Validation is an open source library to validate data in your Elixir application.To learn about Elx Validation’s powerful validation features, let’s look at example of validating a form and displaying the error messages back to the user.

Installation

to use validator in phoenix you have to to use this package :

mix.exs{:elx_validation, "~> 0.1.3"}def application do
[
extra_applications: [:elx_validation]
]
end
Terminal> mix deps.get

How Elx Validation work?

Now we are ready to the logic of validate the new user. To do this, we will use the validate method provided by the ElxValidation. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.

sample_data =%{
name: "Majid",
last_name: "Ahmaditabar"
}
rules =[
%{
field: "name",
as: "First Name",
validate: ["required", "alpha", "max:50"]
},
%{
field: "last_name",
as: "Family",
validate: ["required", "alpha", "max:50"]
}
]
validates =ElxValidation.make(sample_data , rules)

field: The Field name that need to validate
as: its optional and use for response error
validate: List of rules and validations

if validation fails

%{
errors: [
name: ["Error Message" , "Error Message"]
],
failed: true
}

if validation success

%{
errors: [],
failed: false
}

Validation in Phoenix

validates = ElxValidation.make(
%{
name: params["first_name"], last_name: params["last_name"],},
[
%{
field: "name",
as : "First Name",
validate: ["required", "alpha", "max:128"]
},
%{
field: "last_name",
validate: ["required", "alpha", "max:128"]
}
])
if validates.failed do json(
conn,
%{
result: false,
errors: Map.new(validates.errors)
}
)
else
json(
conn,
%{
result: true,
msg: "Validation Passed!"
}
)
end

first_name must be only contains alphabets so if first_name = “Majid123” it’ll be fail because of the digits inside the value, notice that first_name rule has “as” so returned error message will appear with “as” value(as: “First Name”).

{
"errors": {
"name": [
"The First Name may only contain letters."
],
},
"result": false
}

Elx Validation logics :

References

--

--