AFAIK persistent doesn't have any built-in hooks for validation, this is what I use (combined with yesod's i18n):
-- | Represents an entity that has validation logic
class Validatable e where
-- | A set of validations and error messages for a
-- given entity.
validations :: e -> [(Bool, AppMessage)]
validations _ = []
-- | Validate an entity and respond with a Bool wrapped in
-- a writer with potential error messages. By default this
-- makes use of @validations e@
validate :: e -> (Bool, [AppMessage])
validate e = runWriter $ foldM folder True $ validations e
where
folder a (v, m) | v = return $ a && True
| otherwise = tell [m] >> return False
And define your validations:
instance Validatable Stock where
validations e = [ ((0<) . stockInventory $ e, MsgPurchaseErrorInventoryNegative)
, ((0<) . unMoney . stockPrice $ e, MsgPurchaseErrorPriceNegative)
, (maybe True ((0<) . unMoney) . stockCostPrice $ e, MsgPurchaseErrorCostPriceNegative)
, ((2<=) . length . stockName $ e, MsgPurchaseErrorNameTooShort)
]
And then in your handler:
let (isvalid, errors) = validate s
unless isvalid $ invalidArgsI errors