Skip to content

Commit

Permalink
Helper to allow validateField to work on Maybe values (#1879)
Browse files Browse the repository at this point in the history
* Add validateMaybe

* Update docs

* Revert flake.lock changes

* Revert flake.lock
  • Loading branch information
amitaibu authored Dec 30, 2023
1 parent 9fe2cde commit 709e52d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Guide/validation.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
24 changes: 24 additions & 0 deletions IHP/ValidationSupport/ValidateField.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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") ""
Expand Down

0 comments on commit 709e52d

Please sign in to comment.