digitallyinduced/ihp

allow `validateField` to work on Maybe values

amitaibu opened this issue · 2 comments

validateField :: forall field fieldValue model. (
KnownSymbol field
, HasField field model fieldValue
, HasField "meta" model MetaBag
, SetField "meta" model MetaBag
) => Proxy field -> Validator fieldValue -> model -> model
validateField field validator model = attachValidatorResult field (validator (getField @field model)) model
{-# INLINE validateField #-}

Right now validateField assumes we have required fields. So if we have a Maybe Text for the body it won't work.
So this won't work as is:

buildPost post = post
    |> fill @'["title", "sourceUrl"]
    |> validateField #name nonEmpty
    |> validateField #sourceUrl isUrl

@mpscholten we could add validateMaybeField, but I think validateField "just" working would be nicer. Do you agree?

Maybe a simpler option is to add this

-- | Validate a Maybe field.
validateMaybe :: (val -> ValidatorResult) -> Maybe val -> ValidatorResult
validateMaybe _ Nothing = Success
validateMaybe validator (Just value) = validator value

So then we can have this working:

buildPost post = post
    |> fill @'["title", "sourceUrl"]
    |> validateField #name nonEmpty
    |> validateField #sourceUrl (validateMaybe isUrl)

The validateMaybe function looks great. Making validateField work automatically with Maybe fields will add a lot of complexity, so I prefer how you solved it 👍