从数据库 Yesod 验证字段
validate field from database Yesod
您好,我想创建一个只接受 table(超过 20000 行)中存在的值的文件,所以我有以下代码
demoForm :: Maybe Demo -> AForm Handler Demo
demoForm demo = Demo
<$> areq nitField (bfs (MsgName)) (demoFieldOne <$> demo)
<*> areq intField (bfs (MsgName)) (demoFieldTwo <$> demo)
where
errorMessage :: Text
errorMessage = "the company no exist!"
nitField = check validateNit textField
validateNit nit
| companiesMatch nit = Left errorMessage
| otherwise = Right nit
companiesMatch name = do
entities <- runDB $ selectList [CompanyName ==. name] []
return (null entities)
但我收到错误 Couldn't match expected type ‘Bool’with actual type ‘m0 (HandlerT site0 IO Bool)’
那么如何从 monad 获取 bool 值或存在更好的方法来进行此验证?
谢谢@Michael Snoyman,你是对的,我只需要使用 checkM
demoForm :: Maybe Demo -> AForm Handler Demo
demoForm demo = Demo
<$> areq nitField (bfs (MsgName)) (demoFieldOne <$> demo)
<*> areq intField (bfs (MsgName)) (demoFieldTwo <$> demo)
where
nitField = checkM validateNit textField
validateNit input = do
mbNit <- runDB $ selectList [CompanyName ==. input] []
return $ case null mbNit of
True -> Left (MsgErrNit :: AppMessage)
False -> Right input
您好,我想创建一个只接受 table(超过 20000 行)中存在的值的文件,所以我有以下代码
demoForm :: Maybe Demo -> AForm Handler Demo
demoForm demo = Demo
<$> areq nitField (bfs (MsgName)) (demoFieldOne <$> demo)
<*> areq intField (bfs (MsgName)) (demoFieldTwo <$> demo)
where
errorMessage :: Text
errorMessage = "the company no exist!"
nitField = check validateNit textField
validateNit nit
| companiesMatch nit = Left errorMessage
| otherwise = Right nit
companiesMatch name = do
entities <- runDB $ selectList [CompanyName ==. name] []
return (null entities)
但我收到错误 Couldn't match expected type ‘Bool’with actual type ‘m0 (HandlerT site0 IO Bool)’
那么如何从 monad 获取 bool 值或存在更好的方法来进行此验证?
谢谢@Michael Snoyman,你是对的,我只需要使用 checkM
demoForm :: Maybe Demo -> AForm Handler Demo
demoForm demo = Demo
<$> areq nitField (bfs (MsgName)) (demoFieldOne <$> demo)
<*> areq intField (bfs (MsgName)) (demoFieldTwo <$> demo)
where
nitField = checkM validateNit textField
validateNit input = do
mbNit <- runDB $ selectList [CompanyName ==. input] []
return $ case null mbNit of
True -> Left (MsgErrNit :: AppMessage)
False -> Right input