输入验证
验证事例
Lapis 附带了一组用于处理外部输入的校验器。这里有一个简单的例子:
local lapis = require("lapis")
local app_helpers = require("lapis.application")
local validate = require("lapis.validate")
local capture_errors = app_helpers.capture_errors
local 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 : 值要等于 xxxtype: 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
end
local app_helpers = require("lapis.application")
local capture_errors = app_helpers.capture_errors
local 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 ,而不是产生错误
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。