Skip to content

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:

bash
Guard ➔ Validator ➔ Interceptor ➔ Route Handler

Applying a Validator (--@Validator) ​

To validate incoming data on a route, place the --@Validator(...) attribute comment directly above your route function:

luau
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 User

Writing 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.

luau
-- 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:

OptionTypeDescription
typestring?Expected Luau primitive type (e.g., "string", "number", "boolean", "table").
requiredboolean?Whether the field must be present in the body.
minnumber?Minimum character length for strings, or minimum numeric value for numbers.
maxnumber?Maximum character length for strings, or maximum numeric value for numbers.
patternstring?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:

OptionTypeDescription
requiredboolean?Whether the parameter or query key must be present.
minnumber?Minimum character length for the string value.
maxnumber?Maximum character length for the string value.
patternstring?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:

json
{
    "message": [
        "username must be at least 3 characters",
        "email does not match expected pattern"
    ],
    "error": "Bad Request"
}