4
有沒有辦法在每個update/replace
或insert
之前執行自定義驗證(某種鉤子),並在驗證失敗時返回消息?就像它可以在ActiveModel
中完成一樣。是否有方便的方式來執行Haskell持久性模型驗證?
我只能寫一個驗證函數,但我需要重寫所有更新或插入此模型的地方。
有沒有辦法在每個update/replace
或insert
之前執行自定義驗證(某種鉤子),並在驗證失敗時返回消息?就像它可以在ActiveModel
中完成一樣。是否有方便的方式來執行Haskell持久性模型驗證?
我只能寫一個驗證函數,但我需要重寫所有更新或插入此模型的地方。
AFAIK持久不具有驗證任何內置掛鉤,這是我使用(並結合耶索德的國際化):
-- | 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 [email protected]
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
,並定義驗證:
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)
]
而且然後在您的處理程序中:
let (isvalid, errors) = validate s
unless isvalid $ invalidArgsI errors