Lapis输入验证

我在学习 Lua/Lapis,遇到了问题。

现有情况:当验证失败时,控制器会显示一个视图(我不知道是哪一个)。当验证通过时,登录视图会正确显示。

期望的情况:当输入验证失败时,我希望渲染带有错误消息的注册视图。当验证通过时,应重定向到登录视图。

这是我的控制器:

app:post("/signup", capture_errors(function(self)
  validate.assert_valid(self.params, {
    { "email", exists = true },
    { "password", exists = true },
    { "confirm_password", equals = self.params.password }
  })

  return { redirect_to = "/signin" }
end))

谢谢!

点赞
用户127833
用户127833

capture_errors 提供了一个默认的错误处理函数,如下所示:

function() return { render = true } end

请参见http://leafo.net/lapis/reference/utilities.html#application-helpers-safe_fn--capture_errorsfn_or_tbl

它的作用是渲染该操作的默认视图。当您要在表单页面上显示错误时,这非常有用。

为了覆盖错误处理函数,您可以编写以下代码:

app:post("/signup", capture_errors({
  on_error = function(self)
    return { redirect_to = "/signin" }
  end,
  function(self)
    validate.assert_valid(self.params, {
      { "email", exists = true },
      { "password", exists = true },
      { "confirm_password", equals = self.params.password }
    })

    return { redirect_to = "/signin" }
  end
}))

您可以在参考手册中查看完整示例:http://leafo.net/lapis/reference/exception_handling.html#capturing-recoverable-errors

我不建议在 POST 请求中进行重定向,因为您无法访问错误消息(通常在同一请求中的 self.errors 中)。

2015-10-02 03:00:14