haskellyesodyesod-forms

validate field from database Yesod


Hi i want create a file that only accept values that exist in a table (with more that 20000 rows) so i have the following code

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)

but I get the error Couldn't match expected type ‘Bool’with actual type ‘m0 (HandlerT site0 IO Bool)’ so how can get the bool value from the monad or exist a better way to do this validations?


Solution

  • thanks @Michael Snoyman you are rigth I just have to use 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