Repository navigation
Validation
Laravex provides a Laravel-compatible validation layer in Laravex.Validation. Rules are declared as pipe-separated strings, lists, or module atoms. Validation errors are flashed to the session automatically, and failed web requests redirect back to the form.
alias Laravex.Validation
{:ok, validated} = Validation.validate(request.params, %{
"email" => "required|email",
"name" => "required|min:2|max:255"
})Returns {:ok, validated_map} on success or {:error, errors_map} on failure.
validate!/3 raises Laravex.Validation.Error instead of returning {:error, …}:
validated = Validation.validate!(request.params, %{
"title" => "required|string|max:200",
"body" => "required"
})For web controller actions, use validate_request/3. It flashes errors and old input to the session, then raises Laravex.Validation.Failed so the kernel can redirect back automatically:
def store(request) do
{:ok, validated, request} =
Validation.validate_request(request, %{
"title" => "required|string|max:200",
"body" => "required"
})
# only reached when validation passes
Post.create!(validated)
redirect("/posts")
endFor JSON requests (Accept: application/json or X-Requested-With: XMLHttpRequest), validate_request/3 returns {:error, errors, request} with a 422 JSON response instead of redirecting.
Form Requests encapsulate authorization and validation rules in a dedicated module. The Laravex.Http.FormRequest behaviour provides the structure.
defmodule App.Http.Requests.StorePost do
use Laravex.Http.FormRequest
def authorize(_request), do: true # optional — defaults to true
def rules do
%{
"title" => "required|string|max:200",
"body" => "required|string",
"tags" => "array"
}
end
# optional — override error messages
def messages do
%{"title.required" => "A post title is required."}
end
# optional — override field labels in messages
def attributes do
%{"body" => "post body"}
end
endDeclare the form request module in the route options:
Router.post("/posts", {PostController, :store},
form_request: App.Http.Requests.StorePost)The kernel resolves and runs the FormRequest before invoking the controller. When authorization fails, a 403 Forbidden is raised. When validation fails, the request is redirected back (or returns 422 for JSON).
Validated data is available on request.validated:
def store(request) do
Post.create!(request.validated)
redirect("/posts")
endRules may be provided as a pipe-separated string, a list, or a mix:
%{"field" => "required|string|max:255"}
%{"field" => ["required", "string", "max:255"]}| Rule | Description |
|---|---|
bail |
Stop validating this field after the first failure |
| Rule | Description |
|---|---|
required |
Field must be present and not blank |
sometimes |
Only validate when the field is present |
present |
Field key must exist (value may be blank) |
present_if:other,value |
Must be present when other equals value
|
present_unless:other,value |
Must be present unless other equals value
|
filled |
When present, must not be blank |
nullable |
Allow nil; skip further rules |
missing |
Field must be absent |
missing_if:other,value |
Must be missing when other equals value
|
missing_unless:other,value |
Must be missing unless other equals value
|
| Rule | Description |
|---|---|
required_if:other,value |
Required when other equals value
|
required_unless:other,value |
Required unless other equals value
|
required_with:foo,bar |
Required when any of the listed fields are filled |
required_with_all:foo,bar |
Required when all listed fields are filled |
required_without:foo,bar |
Required when any listed field is absent |
required_without_all:foo,bar |
Required when all listed fields are absent |
| Rule | Description |
|---|---|
prohibited |
Field must be absent/blank |
prohibited_if:other,value |
Prohibited when other equals value
|
prohibited_unless:other,value |
Prohibited unless other equals value
|
prohibits:a,b |
When present, the listed fields must be absent |
| Rule | Description |
|---|---|
string |
Must be a string |
integer |
Must be an integer (or parsable integer string) |
numeric |
Must be numeric (integer or float) |
decimal |
Must be numeric; optionally decimal:2 (exactly 2 d.p.) or decimal:1,3 (1–3 d.p.) |
boolean |
Must be true, false, 1, 0, "1", "0", "true", "false"
|
array |
Must be a list or map |
json |
Must be a valid JSON string |
ip |
Must be a valid IPv4 or IPv6 address |
ipv4 |
Must be a valid IPv4 address |
ipv6 |
Must be a valid IPv6 address |
mac_address |
Must match XX:XX:XX:XX:XX:XX or XX-XX-XX-XX-XX-XX
|
lowercase |
Must be entirely lowercase |
uppercase |
Must be entirely uppercase |
ascii |
Must contain only ASCII characters (0x00–0x7F) |
hex_color |
Must be a valid hexadecimal colour (#RGB, #RRGGBB, #RRGGBBAA) |
ulid |
Must be a valid ULID (Crockford Base32, 26 characters) |
| Rule | Description |
|---|---|
min:n |
Minimum length (strings), minimum value (numbers), minimum KB (files) |
max:n |
Maximum length (strings), maximum value (numbers), maximum KB (files) |
between:min,max |
Character length or numeric value between min and max (inclusive) |
size:n |
Exact length (strings) or exact count (lists) |
digits:n |
Exactly n digits |
digits_between:min,max |
Between min and max digits |
multiple_of:n |
Numeric value must be a multiple of n
|
| Rule | Description |
|---|---|
email |
Must contain @
|
url |
Must be a valid HTTP/HTTPS URL |
uuid |
Must match UUID v1–v5 format |
ulid |
Must be a valid ULID |
alpha |
Letters only (Unicode) |
alpha_num |
Letters and numbers only (Unicode) |
alpha_dash |
Letters, numbers, dashes, and underscores (Unicode) |
ascii |
ASCII characters only |
hex_color |
Valid hex colour |
lowercase |
Must be lowercase |
uppercase |
Must be uppercase |
regex:pattern |
Must match the given regular expression |
date |
Must be a valid ISO 8601 date or datetime |
date_format:format |
Must match the given date format (Y-m-d or Y-m-d H:i:s) |
| Rule | Description |
|---|---|
same:other |
Must match another field's value |
different:other |
Must differ from another field's value |
confirmed |
Must match a {field}_confirmation field |
gt:other |
Numerically greater than another field or literal |
gte:other |
Greater than or equal to |
lt:other |
Less than |
lte:other |
Less than or equal to |
after:date |
Must be a date after the given date or field |
after_or_equal:date |
Must be a date on or after the given date or field |
before:date |
Must be a date before the given date or field |
before_or_equal:date |
Must be a date on or before the given date or field |
| Rule | Description |
|---|---|
in:a,b,c |
Value must be in the given list |
not_in:a,b,c |
Value must not be in the given list |
starts_with:a,b |
Must start with one of the given prefixes |
doesnt_start_with:a,b |
Must not start with any of the given prefixes |
ends_with:a,b |
Must end with one of the given suffixes |
doesnt_end_with:a,b |
Must not end with any of the given suffixes |
contains:a,b |
Must contain one of the given values (string or array) |
doesnt_contain:a,b |
Must not contain any of the given values |
distinct |
Array field must have no duplicate values |
required_array_keys:a,b |
Array/map must contain all of the given keys |
| Rule | Description |
|---|---|
accepted |
Must be true, 1, "1", "true", "yes", or "on"
|
accepted_if:other,value |
Must be accepted when other equals value
|
declined |
Must be false, 0, "0", "false", "no", or "off"
|
declined_if:other,value |
Must be declined when other equals value
|
| Rule | Description |
|---|---|
file |
Must be an UploadedFile struct |
image |
Must be an UploadedFile with an image MIME type |
mimes:jpg,png |
File extension must be in the given list |
extensions:jpg,png |
Alias for mimes — file extension must match |
mimetypes:image/jpeg,image/png |
MIME type must be in the given list |
dimensions:width=200,height=100 |
Image dimensions must satisfy the constraints |
| Rule | Description |
|---|---|
unique:table,column,ignore_id |
Value must not already exist in the database |
exists:table,column |
Value must exist in the database |
| Rule | Description |
|---|---|
password |
Minimum 8 characters |
password:letters,mixed,numbers,symbols |
Flags: letters (≥1 letter), mixed (upper + lower), numbers (≥1 digit), symbols (≥1 symbol) |
current_password |
Must match the authenticated user's current password |
Example: "password:letters,numbers,symbols" requires at least one letter, one number, and one symbol (minimum 8 characters).
| Rule | Description |
|---|---|
exclude |
Always exclude this field from the validated output |
exclude_if:other,value |
Exclude when another field equals the given value |
exclude_unless:other,value |
Exclude unless another field equals the given value |
exclude_with:other |
Exclude when any of the listed fields are present |
exclude_without:other |
Exclude when any of the listed fields are absent |
Validate array elements with *:
%{
"tags" => "array",
"tags.*" => "string|max:50"
}Implement the Laravex.Validation.Rule behaviour for reusable custom rules:
defmodule App.Rules.Uppercase do
@behaviour Laravex.Validation.Rule
def passes?(_attribute, value) do
is_binary(value) and value == String.upcase(value)
end
def message, do: "The :attribute must be uppercase."
endUse the module atom directly in a rule list:
%{"code" => ["required", App.Rules.Uppercase]}The rule module may also export a 3-arity passes?/3 (receives attribute, value, data) or validate/3 (returns :ok or {:error, message}).
Pass :messages and :attributes options to validate/3 or validate_request/3:
Validation.validate(data, rules,
messages: %{
"email.required" => "We need your email address.",
"name.min" => "Your name is too short."
},
attributes: %{
"email" => "email address"
}
)The :attribute placeholder in messages is replaced with the attribute label. Field and dot-notation rule keys (field.rule) are both supported.
Errors are automatically flashed to the session and merged into every view as the errors map. Access them with @error:
<input type="email" name="email" value="{{ old('email') }}">
@error('email')
<p class="text-danger">{{ $message }}</p>
@enderror-
Requests —
Request.validate/2for inline validation -
Blade-Templates#Validation Errors —
@errordirective - Session — flash mechanics for errors and old input
-
Error-Handling — how
Laravex.Validation.Failedis rendered
Laravex — Laravel-faithful application skeleton & runtime for Elixir.
GitHub
·
Docs
·
Limitations
·
Laravel Docs
Not affiliated with Laravel LLC or the Elixir core team. Built to feel like Laravel on the BEAM.
- Home
- Installation
- Configuration
- Directory-Structure
- Request-Lifecycle
- Service-Container
- Service-Providers
- Deployment
- Routing
- Middleware
- CSRF-Protection
- Controllers
- Requests
- Responses
- Views
- Blade-Templates
- Asset-Bundling
- Session
- Validation
- Error-Handling
- Logging
- Artisan-Console
- Broadcasting
- Cache
- Collections
- Events
- File-Storage
- Helpers
- HTTP-Client
- Localization
- Notifications
- Pipeline
- Queues
- Rate-Limiting
- Strings
- Task-Scheduling