lapis的输入验证

编程入门 行业动态 更新时间:2024-10-28 14:31:10

<a href=https://www.elefans.com/category/jswz/34/1693045.html style=lapis的输入验证"/>

lapis的输入验证

输入验证

验证事例

Lapis 附带了一组用于处理外部输入的校验器。这里有一个简单的例子:

local lapis = require("lapis")
local app_helpers = require("lapis.application")
local validate = require("lapis.validate")local capture_errors = app_helpers.capture_errorslocal app = lapis.Application()app:match("/create-user", capture_errors(function(self)validate.assert_valid(self.params, {{ "username", exists = true, min_length = 2, max_length = 25 },{ "password", exists = true, min_length = 2 },{ "password_repeat", equals = self.params.password },{ "email", exists = true, min_length = 3 },{ "accept_terms", equals = "yes", "You must accept the Terms of Service" }})create_the_user(self.params)return { render = true }
end))return app

assert_valid 接受两个参数,第一个是要被验证的参数表,第二个是一个数组表,它是要要执行验证的列表。每个验证的格式如下

{ Validation_Key, [Error_Message], Validation_Function: Validation_Argument, ... }

上述的Validation_Key 是从正在验证的表中提取的键。

可以提供任何数量的验证函数。如果验证函数需要多个参数,则可以传递一个数组表

第二个位置的 Error_Message 是可选的。如果提供,它将被用来当作验证失败后的错误消息,而不是使用默认生成的。由于 Lua 表的工作方式,它也可以在验证函数之后提供,如上例所示。

验证函数

exists: true : 检查值是否存在,并且不是一个空字符串
file_exists: true : 检查值是否为文件上传
min_length: Min_Length : 值必须至少为 Min_Length 个字符
max_length: Max_Length : 值最多必须为 Max_Length 个字符
is_integer: true : 值匹配整数模式
is_color: true : 值匹配 CSS 的十六进制颜色(例如#1234AA
is_file: true : 值要是一个上传的文件
equals: String : 值要等于 xxx
type: String : 值要是 String 类型
one_of: {A, B, C, ...} : 值要等于数组表中的其中一个元素

创建自定义验证器

自定义验证器可以这样定义:

local validate = require("lapis.validate")validate.validate_functions.integer_greater_than = function(input, min)local num = tonumber(input)return num and num > min, "%s must be greater than " .. min
endlocal app_helpers = require("lapis.application")
local capture_errors = app_helpers.capture_errorslocal app = lapis.Application()app:match("/", capture_errors(function(self)validate.assert_valid(self.params, {{ "number", integer_greater_than = 100 }})
end))

手动验证

除了 assert_valid ,还有一个有用的验证函数:

local validate = require("lapis.validate").validate

validate(object,validation) - 使用与 assert_valid 完全相同的参数,但在失败时返回错误或 nil ,而不是产生错误

更多推荐

lapis的输入验证

本文发布于:2024-02-17 06:35:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1693034.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:lapis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!