4

有什么方法可以在每个之前执行自定义验证(某种钩子),update/replace或者insert在验证失败时返回一条消息?就像它可以在ActiveModel.

我可以只写一个验证函数,但我需要重写我更新或插入这个模型的所有地方。

4

1 回答 1

1

AFAIK persistent 没有任何用于验证的内置钩子,这是我使用的(结合 yesod 的 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

并定义您的验证:

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
于 2015-06-12T06:27:31.840 回答