Skip to content

Commit

Permalink
add trim option to validator
Browse files Browse the repository at this point in the history
  • Loading branch information
AMD-NICK committed Dec 8, 2023
1 parent db93860 commit 3cd4214
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ app:use( rate_limiter{
```lua
local validator = require("validator").middleware
app:get("/", validator({
steamid = "required|string|starts_with:765|size:17",
steamid = "required|string|trim|starts_with:765|size:17",
amount = "required|integer|min:1|max:100",
sum = "optional|decimal|min:1.5|max:99.5",
}), function(req, res, next)
Expand Down
10 changes: 7 additions & 3 deletions lua/validator.lua
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ rulesets["string"] = function(value)
end
end

rulesets["trim"] = function(value)
return value:match("^%s*(.-)%s*$")
end

rulesets["match"] = function(value, patt)
return ({value:match(patt)})[1] -- return only one value
end
Expand Down Expand Up @@ -173,8 +177,8 @@ local function express_middleware(params_with_rules, messages) -- messages may b
end

local formatted_values, errors = validate_all(params_with_rules, params_values, messages)
if next(errors) then
local param_name, msg = next(errors)
if errors then
local param_name, msg = _G.next(errors)
next({
message = "Parameter validation failed. " .. param_name .. ": " .. msg,
status = 400,
Expand All @@ -187,7 +191,7 @@ local function express_middleware(params_with_rules, messages) -- messages may b
end

if req.valid then print("validator: Some of middlewares already created the req.valid field. Override") end
req.valid = params_values
req.valid = formatted_values

next()
end
Expand Down

0 comments on commit 3cd4214

Please sign in to comment.