Validator
A Validator checks incoming request data before it reaches your handler function. If any field fails validation, Mayari automatically halts the request and responds with a 400 Bad Request listing every error. If everything passes, the request moves forward.
Validators execute after Guards and before Interceptors:
Guard ➔ Validator ➔ Interceptor ➔ Route HandlerApplying a Validator (--@Validator)
To validate incoming data on a route, place the --@Validator(...) attribute comment directly above your route function:
local common = require("common")
local response = common.response
local User = {}
--@Validator(CreateUser)
function User.Post(req: IRequest)
return response.json({ message = "User created successfully!" })
end
return UserWriting Validator Rules (src/validators/)
Validator rule files must live in src/validators/ (e.g., --@Validator(CreateUser) maps to src/validators/CreateUser.luau).
Each rule file exports a table with schemas for up to three target inputs: body, params, and query. You only need to define the targets you want to inspect.
-- src/validators/CreateUser.luau
return {
body = {
username = { type = "string", required = true, min = 3, max = 20 },
email = { type = "string", required = true, pattern = "^[%w.]+@[%w]+%.[%a]+$" },
age = { type = "number", required = true, min = 13 },
},
query = {
ref = { required = false, min = 3 },
},
}Validation Options
Body Schema Options (body)
Used for JSON, form data, or raw text payloads in req.body:
| Option | Type | Description |
|---|---|---|
type | string? | Expected Luau primitive type (e.g., "string", "number", "boolean", "table"). |
required | boolean? | Whether the field must be present in the body. |
min | number? | Minimum character length for strings, or minimum numeric value for numbers. |
max | number? | Maximum character length for strings, or maximum numeric value for numbers. |
pattern | string? | Lua pattern match string (commonly used for email/format checking). |
Parameter & Query Schema Options (params / query)
Used to validate URL path segments (req.params) or search params (req.query). Since URL values are always strings, the type option is omitted:
| Option | Type | Description |
|---|---|---|
required | boolean? | Whether the parameter or query key must be present. |
min | number? | Minimum character length for the string value. |
max | number? | Maximum character length for the string value. |
pattern | string? | Lua pattern match string. |
4. Error Responses
Mayari evaluates all fields before returning a response. If one or more fields fail validation, Mayari stops execution and responds with status 400 Bad Request containing a list of every validation error:
{
"message": [
"username must be at least 3 characters",
"email does not match expected pattern"
],
"error": "Bad Request"
}