从数据库Yesod验证字段

时间:2016-10-21 17:03:12

标签: haskell yesod yesod-forms

您好我想创建一个只接受表中存在的值的文件(超过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值或者存在更好的方法来进行此验证?

1 个答案:

答案 0 :(得分:1)

感谢@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