2014-01-06 30 views

回答

1

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 
相關問題