diff --git a/Guide/validation.markdown b/Guide/validation.markdown index 6938f93c8..b88eeb925 100644 --- a/Guide/validation.markdown +++ b/Guide/validation.markdown @@ -94,6 +94,18 @@ Works with ints: You can find [the full list of built-in validators in the API Documentation](https://ihp.digitallyinduced.com/api-docs/IHP-ValidationSupport-ValidateField.html). +### Validate `Maybe` Fields. + +You can use all the existing validators with `Maybe` fields. The validator will only be applied when the field is not `Nothing`. + +```haskell +buildPost :: Post -> Post +buildPost post = post + |> validateField #title nonEmpty + -- Assuming sourceUrl is optional. + |> validateField #sourceUrl (validateMaybe nonEmpty) +``` + ### Fill Validation When using [`fill`](https://ihp.digitallyinduced.com/api-docs/IHP-Controller-Param.html#v:fill), like `|> fill @'["title", "body"]`, any error parsing the input is also added as a validation error. diff --git a/IHP/ValidationSupport/ValidateField.hs b/IHP/ValidationSupport/ValidateField.hs index 045ac1e8c..ba516ef04 100644 --- a/IHP/ValidationSupport/ValidateField.hs +++ b/IHP/ValidationSupport/ValidateField.hs @@ -99,6 +99,30 @@ validateFieldIO fieldProxy customValidation model = do pure (attachValidatorResult fieldProxy result model) {-# INLINE validateFieldIO #-} +-- | Validate a Maybe field. +-- +-- Validate a Maybe field using a given validator function. +-- >>> validateMaybe nonEmpty (Just "foo") +-- Success +-- +-- >>> validateMaybe nonEmpty (Just "") +-- Failure "This field cannot be empty" +-- +-- If the value is 'Nothing', the validation will succeed. +-- >>> validateMaybe nonEmpty Nothing +-- Success +-- +-- This function is useful when you want to validate a field that is optional. +-- >>> buildPost :: Post -> Post +-- >>> buildPost post = post +-- >>> |> validateField #title nonEmpty +-- >>> -- Assuming sourceUrl is optional. +-- >>> |> validateField #sourceUrl (validateMaybe nonEmpty) +validateMaybe :: (val -> ValidatorResult) -> Maybe val -> ValidatorResult +validateMaybe _ Nothing = Success +validateMaybe validator (Just value) = validator value +{-# INLINE validateMaybe #-} + -- | Overrides the error message of a given validator function. -- -- >>> (nonEmpty |> withCustomErrorMessage "Custom error message") ""