Nex.Validator
(nex_core v0.4.3)
Copy Markdown
Params validation for Nex applications.
Usage
defmodule MyApp.Pages.Users do
use Nex
def create(params) do
case validate(params, %{
"name" => [:required, :string],
"email" => [:required, :string, :email],
"age" => [:number, min: 18]
}) do
{:ok, valid_params} ->
# Create user
{:error, errors} ->
Nex.json(%{errors: errors}, status: 422)
end
end
endValidators
:required- Field must be present and not empty:string- Must be a string:number- Must be a number:boolean- Must be true or false:email- Must be a valid email format:url- Must be a valid URL:min- Minimum length/value (requires :string or :number):max- Maximum length/value (requires :string or :number):format- Regex pattern match:in- Must be in list of allowed values
Custom Validators
def my_validator(value, _opts) do
if valid?(value) do
:ok
else
{:error, "must be valid"}
end
end
validate(params, %{"field" => [:required, {&my_validator/2, [arg1: "value"]}]})
Summary
Types
@type validation_result() :: {:ok, map()} | {:error, [validation_error()]}
Functions
@spec validate(map(), map()) :: validation_result()
Validates params against a schema.
Arguments
params- Map of parameters to validateschema- Map of field names to validator rules
Returns
{:ok, validated_params}- Validation passed{:error, errors}- Validation failed
Examples
validate(%{"name" => "John"}, %{
"name" => [:required, :string]
})
# => {:ok, %{"name" => "John"}}
validate(%{}, %{
"name" => [:required, :string]
})
# => {:error, [{"name", "is required"}]}
Same as validate/2 but raises on validation error.